LoginSignup
0
0

More than 1 year has passed since last update.

[React]フォームをエンターキーで送信する方法

Posted at

はじめに

検索フォームを入力したときに、検索ボタンをわざわざ押すのが面倒だったので、
エンターキーで検索条件を送信する方法を探しました。

やり方

export default function SearchField() {
  const dispatch = useDispatch();
  const [inputText, setInputText] = React.useState("");

  const pressEnter = (e: any) => {
    // ここでエンターキーを指定する
    if (e.key == "Enter") {
      dispatch(
        fetchPresentations({
          query: e.target.value,
        })
      );
    }
  };

  return (
    <Search>
      <SearchIconWrapper>
        <SearchIcon />
      </SearchIconWrapper>
      {/* onKeyDownを使用する */}
      <StyledInputBase placeholder="検索" onKeyDown={(e) => pressEnter(e)} />
    </Search>
  );
}

完成

これで、エンターキーを押すだけで検索することが出来ます。
検索ボタンも必要なくなったので、非表示にしました。

image.png

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