3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React Hook Form入門:useStateを書かずにhandleSubmitでフォーム送信する方法

Posted at

はじめに

Reactでフォームを書くとき、最初は useState と onChange を組み合わせて入力値を管理する人が多いと思います。
でも実は React Hook Form を使えば、これらは不要です。
ここでは「なぜ useState が不要なのか?」と「handleSubmit / onSubmit の役割」を解説します。

問題

よくあるフォームの書き方:

const [userId, setUserId] = useState("");

<input value={userId} onChange={(e) => setUserId(e.target.value)} />
  • 入力管理を useState と onChange でやっていて長い

解決

RHF では register がすでに入力値を管理してくれます。
そのため、useState と onChange は不要になります。

const onSubmit = (data: any) => {
  navigate(`/cards/${data.userId}`);
};

<form onSubmit={handleSubmit(onSubmit)}>
  <input {...register("userId")} placeholder="IDを入力" />
  <button type="submit">送信</button>
</form>

ポイント

  • register("userId") → React Hook Formが自動でstate管理

  • handleSubmit(onSubmit) → 入力値をまとめてdataに渡してくれる

  • onSubmit → 送信時の処理(ここではnavigateでページ遷移)

これだけで「入力管理」と「送信処理」がスッキリまとまる!

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?