LoginSignup
6
2

More than 1 year has passed since last update.

【React】Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option> 

Last updated at Posted at 2022-04-19

Warning: Use the 'defaultValue' or 'value' props on instead of setting 'selected' on < option>

01 - January.jpeg
Reactで↑みたいな、初期値でselected指定もできるselectコンポーネントを作っていたらコンソールから表題のエラーを吐かれた。
ググってみたらReactではselectedが非推奨とのことで、公式を見てもseletedを使った記述がない
公式:https://reactjs.org/docs/forms.html#the-select-tag

エラー本文は

optipnタグにselectedを使わないで、selectタグにvalueかdefaultValueを指定して、これ経由で実装せよ

とのことなので、selectタグのvalue経由で選択状態を制御する様な実装に変えたらコンソールエラーが消えました

SelectInput.tsx
import { useState } from 'react'
//略
const SelectInput = ( {//略} ) => {
//略
  const [currentSelected, setCurrentSelected] = useState<string>('01');

  const changeSelect = (newSelect: string) => {
    setCurrentSelected(newSelect);
  };

  return (
    <select
      onChange={(event) => changeSelect(event.target.value)}
      value={currentSelected}
    >
      {options.map((option: OptionContent) => (
        <option
          value={option.value}
          key={option.content}
          // ここにselectedを書くとエラーになるのでselectedを使うやり方はだめっぽい
        >
          {option.content}
        </option>
      ))}
    </select>
  );
};
export default SelectInput;

以上です!

6
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2