본문 바로가기

코딩도 합니다/React

[리액트 에러 React/RN Error] A component is changing an uncontrolled input of type undefined to be controlled.



안녕하세요.

디자인도 하고 개발도 하는 '디발자 뚝딱'입니다.

 

이번 포스팅에서는 리액트 혹은 리액트네이티브로 개발하다가 만날 수 있는 Warning: A component is changing an uncontrolled input of type undefined to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. 에러 해결 방법에 대해 알아보겠습니다.

 

먼저 이 에러를 번역해 볼게요.

구성 요소가 제어할 정의되지 않은 유형의 제어되지 않은 입력을 변경하고 있습니다. 입력 요소는 제어되지 않음에서 제어됨으로(또는 그 반대로) 전환되어서는 안 됩니다. 구성 요소의 수명 동안 제어 또는 제어되지 않은 입력 요소를 사용할지 결정합니다.

 

여기서 중요한 건 '정의되지 않은 유형'입니다.

즉, input에 값이 undefined인 경우를 생각해서 value에 빈 값("")을 넣어주면 됩니다.

 

에러가 발생한 코드를 먼저 봐볼까요?

  에러 발생한 코드

const [text, setText] = useState();

return(
	<input onChange={(value) => setText(value)} value={text} />
)

 

 

  에러 해결한 코드

value 안에 || ""만 넣어주면 되는 간단한 에러였습니다.

const [text, setText] = useState();

return(
	<input onChange={(value) => setText(value)} value={text || ""} />
)

 

 

 

 

 

 

728x90