[React] A component is changing a controlled input to be uncontrolled.

sujipark-fe·2024년 7월 26일

React

목록 보기
5/7

이슈

설명 input만 수정가능한 코드 작성 중 이런 에러가 떴습니다. 에러메세지는 아래와 같습니다.

A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components

작성 코드는 다음과 같습니다. 겉보기엔 문제가 없어보이는데요..

  const [currentTarget, setCurrentTarget] = useState({
    category: "",
    name: "",
    description: ""
  });

const handleChange = (e) => {
  const { name, value } = e.target;
  setCurrentTarget((prev) => ({ ...prev, [name]: value }));
};

return (
  <form onSubmit={handleSubmit}>
  	...
	<span>설명</span>
      <p>
  		<input
          type="text"
          value={currentTarget.description}
          onChange={handleChange}
		/>
      </p>
  </form>
)

원인

이 에러는 일반적으로 React에서 value 속성과 onChange 핸들러를 함께 사용하지 않거나, value가 undefined로 설정되어 발생합니다. 위 코드의 경우 후자인데요. React는 입력을 제어할 수 없게 되어 에러를 발생시킵니다.

위 코드에서 currentTarget.description이 undefined가 될 가능성 때문에 발생할 수 있습니다. 실제로 값이 있었기 때문에 undefined가 된 건 아니지만, 그럴수도 있는 "가능성" 때문입니다.

해결

이를 방지하기 위해 상태가 초기화될 때 빈 문자열로 설정하거나, 값이 undefined일 때 빈 문자열로 대체할 수 있습니다.

<input
  type="text"
  name="description"
  value={currentTarget.description || ""} // || "" 추가
  onChange={handleChange}
/>

위와 같이 value에 값이 없을 때 빈 문자열을 대체하도록 하면 됩니다.
단 4글자로 이슈를 해결했네요.

profile
개발 너무 재밌다 재밌어❤️‍🔥

0개의 댓글