240307 개발일지 TIL - Warning: Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>.

The Web On Everything·2024년 3월 7일
0

개발일지

목록 보기
256/269

Warning: Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>.
    at option
    at select
    at label
    at form
    at div
    at SignupForm (webpack-internal:///./src/components/SignupForm.tsx:30:119)
    at Home
    at MyApp (webpack-internal:///./src/pages/_app.tsx:11:18)
    at StyleRegistry (/Users/mac/Desktop/study/devcamp/week1/sign-flow-z2/node_modules/styled-jsx/dist/index/index.js:449:36)
    at eV (/Users/mac/Desktop/study/devcamp/week1/sign-flow-z2/node_modules/next/dist/compiled/next-server/pages.runtime.dev.js:8:22622)
    at eO (/Users/mac/Desktop/study/devcamp/week1/sign-flow-z2/node_modules/next/dist/compiled/next-server/pages.runtime.dev.js:17:1744)
    at eq (/Users/mac/Desktop/study/devcamp/week1/sign-flow-z2/node_modules/next/dist/compiled/next-server/pages.runtime.dev.js:17:3076)
    at div
    at eY (/Users/mac/Desktop/study/devcamp/week1/sign-flow-z2/node_modules/next/dist/compiled/next-server/pages.runtime.dev.js:26:763)

문제 발생

// 문제의 그 코드
<select
	{...register("role")}
	className="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
  <option value="" disabled selected>
    역할을 선택해주세요
  </option>
  <option value="admin">관리자</option>
  <option value="user">일반사용자</option>
</select>

select 박스 사용시 selected 속성을 option에 직접 적용해서 발생한 현상.

문제 원인

React에서 select 박스를 사용할 때, selected 속성을 option에 직접 적용하는 대신, select에 defaultValue 혹은 value 속성을 사용해야 하는데, 경고 메시지는 select 내부의 option 태그에서 selected 속성을 사용하지 말라고 지시하고 알려줌.

해결 방법

<select
  {...register("role")}
  className="mt-1 px-3 py-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
  defaultValue=""
>
  <option value="" disabled>
    역할을 선택해주세요
  </option>
  <option value="admin">관리자</option>
  <option value="user">일반사용자</option>
</select>

defaultValue 속성은 폼이 초기에 렌더링될 때 선택되어야 할 option의 값을 지정한다.

느낀 점

react-hook-form을 사용할 때, register 함수를 통해 양식 상태를 관리하므로 defaultValue 또는 컨트롤 컴포넌트의 value를 사용하는 것이 좋다고 한다.

profile
오늘은 무슨 오류를 만날까?! 널 만나러 가는 길~ LOL

0개의 댓글