フォームのsubmitイベント

Reactでは、<form> タグで囲まれた入力フォームの送信を処理するために、onSubmitイベントを使用します。TypeScript環境ではイベント型の指定が重要です。


1. 基本の書き方(送信時に関数を実行)

const handleSubmit = (e: React.FormEvent
<HTMLFormElement>) => {
  e.preventDefault(); // デフォルトのページリロードを防止
  console.log("送信処理を開始します");
};

const App = () => {
  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="name" />
      <button type="submit">送信</button>
    </form>
  );
};
  • e.preventDefault() を呼ばないと、ページがリロードされてしまいます。
  • イベントの型は `React.FormEvent ` を使います。

2. 入力値を状態管理してsubmitで扱う

import { useState } from "react";

const App = () => {
  const [name, setName] = useState("");

  const handleSubmit = (e: React.FormEvent
<HTMLFormElement>) => {
    e.preventDefault();
    alert(`入力された名前: ${name}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <button type="submit">送信</button>
    </form>
  );
};
  • useStateで状態を管理し、onChangeで値を反映。
  • submit時に最新の状態を処理できます。

3. ボタンのtype指定に注意

<button type="submit">送信</button> // フォーム送信
<button type="button">通常ボタン</button> // 送信されない
  • 明示的にtype="submit"と記述しましょう。省略するとブラウザにより異なる動作になることがあります。

4. イベント型のバリエーション

イベント対象 型の指定例
`
|React.FormEvent`
`
|React.ChangeEvent`
`

✅ イベント型を明確に指定することで、補完や型安全性が向上します。


5. 複数項目を扱う場合(例:オブジェクトで一括管理)

type FormState = {
  name: string;
  email: string;
};

const App = () => {
  const [form, setForm] = useState
<FormState>({
    name: "",
    email: "",
  });

  const handleChange = (e: React.ChangeEvent
<HTMLInputElement>) => {
    const { name, value } = e.target;
    setForm((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    console.log("送信データ:", form);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" value={form.name} onChange={handleChange} />
      <input name="email" value={form.email} onChange={handleChange} />
      <button type="submit">送信</button>
    </form>
  );
};
  • name属性を使って動的にプロパティ更新。
  • 項目が増えてもロジックを簡潔に保てます。
コメントを残す 0

Your email address will not be published. Required fields are marked *