1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】selected属性を使わずにvalue属性を使う

1
Last updated at Posted at 2023-08-12

Reactでselectタグのselected属性を用いて初期選択状態を作ろうとするとエラーが発生する。

<select>
    <option value="apple">Apple</option>
    <option value="banana" selected>Banana</option>
    <option value="grape">Grape</option>    
</select>
// Warning: Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>.

上記のエラーを読み取ると、どうやらReactでselectの初期選択状態を実装したい場合は、selected属性ではなくdefaultValue属性かvalue属性を使用しないといけないとのこと。
React公式ドキュメントにも書かれていました。)

以下のようにvalue属性を用いて実装するとエラーを解消できる。

<select value={ optionState } onChange={ (e)=>setOptionState(e.target.value) }>
    <option value="apple">Apple</option>
    <option value="banana">Banana</option>
    <option value="grape">Grape</option>
</select>

selectタグのvalue属性で指定した値と一致するoptionタグが初期選択状態になる。
また、value属性にステートを用いる場合は、onChangeでステート更新する必要がある。

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?