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?

はじめに

備忘録として記録。わからなかったところをまとめました。

React Hook Formの自動処理

  1. 「入力中の値管理」の自動化入力
    従来の方法ではe.target.valueで入力した値を拾っていたが、React Hook Formでは裏側でよしなに管理してくれる

    *従来の方法 e.target.valueで取得していた値をformDataのstateにsetしていた
    value={formData.title}
    onChange={(e) => setFormData({ ...formData, title: e.target.value })}
    
  2. 「送信時の値取得」の自動化 / handleSubmitの自動処理
    従来の方法では手動でstate管理が必要だが、handleSubmitは登録ボタンが押された時に<form>で囲まれた部分の入力項目の値に対して、送信してくれる

    *従来の方法
    
    *手動でstate管理が必要
    const [formData, setFormData] = useState({ title: "", time: "" });
    
    <input 
      value={formData.title}
      onChange={(e) => setFormData({...formData, title: e.target.value})}
    />
    <button onClick={addRecords}>登録</button>
    
    
    *formDataの値recordsに追加
    const addRecords = () => {
    setRecords([...records, {
      id: nextId++,
      title: formData.title,
      time: Number(formData.time)
    }]);
    setFormData({ title: "", time: "" });
    }  
    
    〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜
    * handleSubmitの場合
    
    onSubmit={handleSubmit(addRecords)}  ←これだけOK
    

registerとは

ざっくばらんに言えば、registerとは入力項目を監視対象として指定するメソッドで、register()の中は、入力項目の名前と具体的な監視する要件を書く場所、といった認識

<input {...register('mail', { required: 'メールを入力してね' })} />

上記の場合inputフォームを監視対象とし、フォーム名は'mail'とし、requiredで空入力でないように監視する。またerrorsの構造は以下のように生成され、エラーメッセージはerrors.title.message値して取り出せる

errors: {
  mail: {
    type: "required",                    // ← requiredから自動生成
    message: "メールを入力してね"         // ← requiredの値から生成
  }
}

バリデーションは優先順位がある

例えば以下のようなコードがあるとする。

<input
            {...register('name', {
              required: '必須入力',
              maxLength: {
                value: 50,
                message: '最大50文字です'
              }
            })}
            type="text"
          />

ここでは表示するエラーが required: '必須入力',message: '最大50文字です'の2つある。
これは混合しないのか?

バリデーションは優先順位がある
通常はrequired → minLength → maxLength → patternの順

参考

react-hook-formで入力内容によってバリデーションする方法
【React】入力のバリデーションはreact-hook-formで決まり!

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?