input에 초기값을 부여할 때 발생하는 적색 콘솔 오류

JH.P·2022년 6월 18일
0
  • 댓글을 수정하는 상황이다.
  • 기존에 작성했던 댓글을 수정하기 위해, 수정 버튼을 누르면 기존의 내용을 불러와 input 태그의 기본값으로 설정하고자 했다.
<ReplyInput
 type="text"
  value={editContent}
  onChange={(event) => {
   setEditContent(event.target.value);
  }}
 />

editContent라는 빈 문자열 state를 input의 value로 지정해주었고,
수정 버튼을 누를 시 아래처럼 value를 갱신한다.

 <FontAwesomeIcon
 icon={faPencil}
  onClick={() => {
    setEditStatus([true, item.id]);
   setEditContent(item.content);
  }}
     />

그러자 콘솔 창에 아래와 같은 에러가 발생하였다.

Warning: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.

내용을 살펴보면, value 속성을 onChange 핸들러를 주지 않은채 부여해서 발생한 에러라고 한다. 이를 해결하기 위해서는 defaultValue 속성을 이용하던지, 아니면 value속성과 함께 readOnly 속성 또는 onChange 핸들러를 작성하여 해결하라고 나와있다. 따라서 아래와 같이 수정했다.

 <ReplyInput
  type="text"
  defaultValue={item.content}
  onChange={(event) => {
    setEditContent(event.target.value);
  }}
   />

input의 기본값을 기존의 컨텐츠로, 그리고 입력 시에는 입력값을 editContent에 갱신되도록 작성한 것이고 수정 버튼 클릭 시에

setEditContent(item.content); 

위 코드는 삭제하였다.

위와 같이 수정하여 정상적으로 해결하였다.

profile
꾸준한 기록

0개의 댓글