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?

【ReactHookForm】getFieldStateの使い方

Posted at

getFieldStateとは

getFieldStateは、React Hook Form v7.25.0で導入されたメソッドで、個別のフィールドの状態を取得できます。型安全な方法でネストされたフィールドの状態を取得したい場合に便利です。

基本的な使い方

import { useForm } from "react-hook-form";

function App() {
  const {
    register,
    getFieldState,
    formState: { isDirty, isValid },
  } = useForm({
    mode: "onChange",
    defaultValues: {
      firstName: "",
    },
  });

  const fieldState = getFieldState("firstName");

  return (
    <form>
      <input {...register("firstName", { required: true })} />
      <p>{getFieldState("firstName").isDirty && "編集済み"}</p>
      <p>{getFieldState("firstName").isTouched && "タッチ済み"}</p>
      <button
        type="button"
        onClick={() => console.log(getFieldState("firstName"))}
      >
        フィールド状態を表示
      </button>
    </form>
  );
}

取得できる状態

getFieldStateで取得できる主な状態は以下のとおりです。

  • isDirty: フィールドが変更されたかどうか
  • isTouched: フィールドがタッチ(フォーカス後にブラー)されたかどうか
  • invalid: フィールドのバリデーションが失敗しているかどうか
  • error: フィールドのエラー情報

注意点

  • フィールド名は、登録されたフィールド名と一致する必要があります
    • 存在しないフィールド名を指定すると、状態はfalse、エラーはundefinedを返します

参考

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?