Warning: A component is changing an uncontrolled input of type checkbox to be controlled

iamsummer__·2020년 10월 28일
2

react로 체크박스 컴포넌트를 개발 중 발생한 에러입니다.

function CheckBox(props) {

  const [isChecked, setCheck] = useState(false);
  
  const handleChange = () => {
    setCheck((isChecked) => {
      return !isChecked;
    });
  }

  return (
    <label>
      <input
         type="checkbox"
         checked={isChecked}
         value={isChecked}
         onChange={handleChange}
      />
      <i className="ico"></i>
      <span className="text">체크박스</span>
    </label>
  );
}
export default Checkbox;

위에 코드에서는 input태그에 onChange이벤트를 통해서 value속성을
state로 제어하고 있어 발생한 warning이었습니다.
value값을 제거하면 해결이 됩니다..

그러나 value값을 제거하면 ..
아래와 같은 warning이 발생합니다. ㅎㅎ

uncontrolled component로 해결했습니다.

function CheckBox(props) {

  const [isChecked, setCheck] = useState(false);
  
  const handleChange = () => {
  }

  return (
    <label>
      <input
         type="checkbox"
         defaultValue={isChecked}
         onChange={handleChange}
      />
      <i className="ico"></i>
      <span className="text">체크박스</span>
    </label>
  );
}
export default Checkbox;

🤔uncontrolled ? controlled컴포넌트에 대해서 알아봅시당!

📚 uncontrolled component

  • react에서 초깃값 지정하고서, 그 이후에 업데이트는 제어하지 않는게 좋습니다.
  • 이러한 경우에는 value대신 defaultValue를 지정하는 것을 권장합니다.
  • state가 외부에 공개되지 않아서 캡슐화가 가능합니다.
  • 불필요한 렌더링을 줄일 수 있습니다.

📚 controlled component

  • react에서 state값으로 데이터를 업데이트 합니다.
  • state값을 통해 엘리먼트의 value값을 제어합니다.
  • 신뢰 가능한 단일 소스'를 기반으로 컴포넌트가 작동되도록 변경
  • state와 사용자의 변화에 따른 sync가 맞기 때문에 실시간 작업 처리 가능

개발하는 내용에 따라 각각 사용하면 좋을 것 같습니다.
예를 들면, 간단한 checkbox의 경우에는 uncontrolled component로,
validation 체크를 해야하는 input의 경우에는 controlled component를 사용하면 좋을 것 같습니다.

참고
https://stackoverflow.com/questions/42522515/what-are-react-controlled-components-and-uncontrolled-components
https://ko.reactjs.org/docs/forms.html#controlled-components
https://hyunseob.github.io/2019/06/02/react-component-the-right-way/
https://soldonii.tistory.com/145
https://github.com/facebook/react/issues/6779

profile
개발하는 프론트엔드개발자

0개의 댓글