0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[React]useStateを使ったフォームの作成方法

Last updated at Posted at 2023-09-03

概要

フォームを作成するにあたって最もスタンダートであるuseStateを使った方法について解説していきたいと思います

ディレクトリ構成

ディレクトリ構成は以下のとおりです

tree
・
├── src
|   └── components
|       └── Form.js
├── App.js
├── index.js
└── styles.css

フォームの作成

Formというコンポーネントを作成します
順番に一つずつ解説していきます

src/components/Form.js
import { useState } from "react";

function Form() {
  const [employeeNumber, setEmployeeNumber] = useState("");
  const [password, setPassword] = useState("");

  const handleSubmit = (e) => {
    // ブラウザで設定されているデフォルトの動作をキャンセルさせる
    e.preventDefault();
    console.log({
      employeeNumber,
      password
    });
  };

  const handleChangeEmployeeNumber = (e) => {
    setEmployeeNumber(e.target.value);
  };
  const handleChangePassword = (e) => {
    setPassword(e.target.value);
  };

  return (
    <div>
      <h1>ログイン画面</h1>
      <form onSubmit={handleSubmit}>
        <div>
          <input
            id="employee_number"
            name="employee_number"
            placeholder="社員番号"
            type="text"
            onChange={handleChangeEmployeeNumber}
          />
        </div>
        <div>
          <input
            id="password"
            name="password"
            placeholder="パスワード"
            type="password"
            onChange={handleChangePassword}
          />
        </div>
        <div>
          <button type="submit">ログイン</button>
        </div>
      </form>
    </div>
  );
}

export default Form;
App.js
import Form from "./components/Form";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <Form />
    </div>
  );
}

form

フォームを作成する際は以下のように

タグを使用します
<div>
    <form onSubmit={handleSubmit}>
    </form>
</div>

ReactのonSubmit関数を使ってフォーム内に入力した値を後述するhandleSubmit関数内で処理します

input

フォーム内にタグを入れて入力欄を作成します

<div>
    <input
        id="employee_number"
        name="employee_number"
        placeholder="社員番号"
        type="text"
        onChange={handleChangeEmployeeNumber}
    />
</div>

inputタグ内の要素は以下のとおりです

要素 説明
id inputタグのid
name 入力欄の名前
placeholder 入力欄が空の時に表示されるテキスト
type 入力欄の型
通常のテキストを入力する場合はtext,パスワードはpasswordにするなど入力したい項目に応じて設定
onChange ReactのEventハンドラ関数の一つ
入力値が変わったときなどに即座に実行されます
inputイベントと同様に動作

input typeの型の一覧は以下を参照してください

button

フォーム内に<button>タグを入れてボタンを作成します
<div>
  <button type="submit">ログイン</button>
</div>

buttonのtypeを"submit"に設定し、formタグ内で定義したonSubmit関数を実行させます

useState

useStateを使って

  • 社員番号
  • パスワード

の状態を管理します
今回は以下の変数、関数名にし、デフォルト値を未入力("")とします

import { useState } from "react";

const [employeeNumber, setEmployeeNumber] = useState("");
const [password, setPassword] = useState("");

onChangeハンドラー

前述したinputタグ内に記載したハンドラーを作成します
このハンドラー関数がないとsubmitする際に値がない状態でsubmitハンドラーに渡されてしまうので
useStateで作成した関数を使用します

const handleChangeEmployeeNumber = (e) => {
    setEmployeeNumber(e.target.value);
};
const handleChangePassword = (e) => {
    setPassword(e.target.value);
};

eって何?

eはReactのイベントオブジェクトで公式ドキュメントによると標準のEventプロパティの一部を実装してるとのことです

const handleChangeEmployeeNumber = (e) => {
    console.log(e)
};
{_reactName: 'onChange', _targetInst: null, type: 'change', nativeEvent: InputEvent, target: HTMLInputElement, …}

eイベントオブジェクト内にtargetというイベントが発生したDOMのノードが含まれており、
e.target.valueからemployeeNumberのDOMのノードから入力した値を取得できます
今回はinput内の値を取得したいので以下のようにsetEmployeeNumber関数内にe.target.valueを記載します

// 社員番号00000001を入力した時
const handleChangeEmployeeNumber = (e) => {
    console.log(e.target.value) // 00000001
    setEmployeeNumber(e.target.value);
};

onSubmitハンドラー

ReactのEventハンドラ関数でフォームが送信されたときに実行されます

const handleSubmit = (e) => {
    // Prevent the browser from reloading the page
    e.preventDefault();
    console.log({
      employeeNumber,
      password
    });
};

e.preventDefault

onSubmitハンドラのデフォルトの挙動について説明すると、ブラウザ側でFormに入力したデータを現在のURLに送信し、ページを更新します
今回はブラウザを再読み込みさせずにsubmitHandlerが実行されたらhandleSubmit内の処理を実行させたいので

e.preventDefault()

と明記することで、デフォルトの処理をオーバーライドさせます

フォームを操作してみよう

フォームに任意の値を入力し、ログインボタンを押します

スクリーンショット 2023-09-03 10.14.46.png

コンソール上に以下のように値が表示されたら成功です

{employeeNumber: '00000001', password: 'test'}

まとめ

今回は非常に簡単なフォームを作成してみました
今後バリデーションやリダイレクト機能も実装してみたいのでまた別の記事を作成してみたいと思います

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?