Home About Contact
HTML , React

HTMLSelectElement で初期状態はどのオプションも選択していない状態をつくる

初期状態:

select-1

選ぶと次のようになるようにしたい:

select-2

もちろん、次のようにあらかじめ先頭に空のオプションを入れておく方式なら簡単。

<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

この記述では空のオプションアイテムが出現してしまう。

select-3

あくまで 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 で実装するには?

これを 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 };

以上です。