
설명 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글자로 이슈를 해결했네요.