LoginSignup
1
0

Reactでインクリメンタルサーチを実装する。

Last updated at Posted at 2023-05-14

Reactでインクリメンタルサーチを実装したので、備忘録として残します。

インクリメンタルサーチとは:
文字を入力していく毎に検索結果が絞り込まれていく検索方式のこと
https://wa3.i-3-i.info/word13753.html

Image from Gyazo

Image from Gyazo

Image from Gyazo

処理の流れ
・絞り込み検索対象の一覧を取得する。
・INPUTに入力した値を保持するuseStateを用意する。
・INPUTに入力するたびhandleChangeファンクションを呼び出すようにする。
・handleChangeファンクションで入力した値をstateにsetさせる。
・stateが更新されたので、コンポーネントが再描画される。
・検索結果が表示される。

  const [searchTerm, setSearchTerm] = useState("");
  const handleChange = (event) => {
    setSearchTerm(event.target.value);
  };

  const filteredCharacters = Object.values(characters).filter((character) => character.name.includes(searchTerm));

   return (
    < div >
      <input
        type="text" autoFocus
        placeholder="検索"
        value={searchTerm}
        onChange={handleChange}
      />

      <table>
        <thead>
          <tr>
            <th>ファイター番号</th>
            <th>ファイター名</th>
          </tr>
        </thead>
        {
          Object.keys(filteredCharacters).map((item) => {
            return (
              <>
                <tbody>
                  <tr>
                    <td>{filteredCharacters[item].no}</td>
                    <td>{filteredCharacters[item].name}</td>
                    <td>詳細</td>
                  </tr>
                </tbody>
              </>
            )
          })
        }
      </table>
    </div >
  )
}

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