LoginSignup
0
0

【React Bootstrap】Enterキーが押された時、Submitボタンを押した時と同じ振る舞いをするようにする。

Last updated at Posted at 2024-05-21

Submitボタンを押す or Enterキーを押した時の振る舞いが同じになる凡例

  • 入力フォームセクションを、submit時の処理関数をプロパティとして持ったFormタグでラップする。
  • Formタグ内のButtonタグのtypeプロパティに、"submit"を指定。

こうすることで、クリックイベントとキーボードイベント(Enterキーを押す)を統合的にウォッチしてくれるようになる。

const onSubmit = (e) => {
 // 入力フォームコンポーネントのデフォルト機能(画面のリロード)を禁止。
  e.preventDefault();
  // Submit時の処理
};

<Form onSubmit={onSubmit}>
  <Form.Control /> //入力フォーム1
  <Form.Control /> //入力フォーム2
  <Button type="submit">Submit</Button> //Submitボタン。
</Form>

簡単なログインフォームで実装する

スクリーンショット 2024-05-21 12.46.48.png

仕様

  • ID、パスワードは入力必須
  • React BootStrapを利用
  • Submitボタンを押す or Enterキーを押す → ログインしました。という文字を表示。

ソースコード


import React from "react";
import { useState } from "react";
import { Form, Button } from "react-bootstrap";

export const EasyLogin = () => {
  const [id, setId] = useState<string>("");
  const [password, setPassword] = useState<string>("");
  const [loginStatus, setLoginStatus] = useState<boolean>(false);

  const onSubmit = (e) => {
    e.preventDefault()
    if (id && password) {
      setLoginStatus(true);
    }
  };

  return (
    <>
      <h1>
        Easy Login
      </h1>
      <Form onSubmit={onSubmit}>
        <Form.Group>
          <Form.Label>ID</Form.Label>
          <Form.Control 
            type="text"
            placeholder="IDを入力"
            value={id}
            onChange={(e) => {setId(e.target.value)}}
          />
          <Form.Label>パスワード</Form.Label>
          <Form.Control 
            type="password"
            placeholder="パスワードを入力"
            value={password}
            onChange={(e) => {setPassword(e.target.value)}}
          />
          <Button 
            type="submit"
            disabled={ !id || !password }
          >
            Submit
          </Button>
        </Form.Group>
      </Form>

      {loginStatus && <h2>ログインしました。</h2>}
    </>
  );
};

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