[React] Error: You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field.

qwe8851·2023년 8월 29일
0

💎 React

목록 보기
36/37
<label htmlFor="1"><input type="radio" id="1" name="completed" value='1' ref={completedRef} checked />완결</label>

위 코드에서 디폴트로 완결을 체크하고싶었는데 아래와 같은 에러가 발생했다.

react-dom.development.js:86 Warning: You provided a checked prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultChecked. Otherwise, set either onChange or readOnly.
at input

해당 경고메시지는 <input type="radio">요소에 checkedprops를 제공했지만, onChange 핸들러가 없는 경우에 나타나며,
checked는 값을 변경하지 않으므로 읽기 전용 필드로 렌더링 됨.

해결 방법은 onChange핸들러를 추가거나 defaultChecked를 사용하면 됨

<input type="radio" id="1" name="completed" value='1' ref={completedRef} defaultChecked />
  완결
</label>

위 코드처럼 defaultChecked를 사용하여 초기 상태를 설정해주는 방식으로 변경해주었다.


+) 아하아하
defaultChecked말고도 defaultValue로 사용하라고 에러뜨길래 value라고 전에 사용햇엇는데 왜 안되는고딩..? 햇는데 두가지방법이 있는것 같더라구요
1. input value={value} onChange={}이런식으로 사용하거나
2. input defaultValue={value} ref={}이런식으로 사용하는 방법

이렇게 두 가지 방법인듯한데,
두번째 방법을 uncontrolled Component방식으로 ref를 사용하면 DOM이 form data를 처리하기 때문에 value를 사용해도 값을 변경할 수 없게 됩니다.
그래서 defaultValue를 사용하여 ref.current.value로 값을 제어하게 하는 방법이라고하네염.






reference : https://velog.io/@jhplus13/react-input%EC%9A%94%EC%86%8C%EC%97%90-value%EC%99%80-defaultValue%EC%9D%98-%EC%B0%A8%EC%9D%B4%EC%A0%90

profile
FrontEnd Developer with React, TypeScript

0개의 댓글