初期状態:
選ぶと次のようになるようにしたい:
もちろん、次のようにあらかじめ先頭に空のオプションを入れておく方式なら簡単。
<select id="targetElement">
<option selected></option>
<option>Pikachu</option>
<option>Squirtle</option>
<option>Golduck</option>
</select>
https://developer.mozilla.org/ja/docs/Web/HTML/Reference/Elements/select
この記述では空のオプションアイテムが出現してしまう。
あくまで option 要素に「空」のオプションはつくりたくない。しかし、初期状態では空になってほしい。 このような場合の実装方法を調べた。(Perplexity に聞いただけです。)
<select id="targetElement">
<option>Pikachu</option>
<option>Squirtle</option>
<option>Golduck</option>
</select>
<script>
document.getElementById('targetElement').selectedIndex = -1;
</script>
HTMLSelectElement のインスタンスを id で指しておいて取得、それの selectedIndex を -1 に設定する。
これを React で実装するには useRef, useEffect を使って次のように実装する:
import { useRef, useEffect } from 'react';
const PokemonSelection = (): React.ReactElement => {
const selectElement = useRef<HTMLSelectElement>(null);
useEffect(()=>{
if( selectElement.current ){
selectElement.current.selectedIndex = -1;
}
};
return (
<select ref={selectElement}>
<option>Pikachu</option>
<option>Squirtle</option>
<option>Golduck</option>
</select>
);
};
export { PokemonSelection };
以上です。