LoginSignup
3
0

More than 3 years have passed since last update.

react-hook-formでフォームに初期値を設定するには

Posted at

概要

以前にreact-hook-formでの値登録に関する記事を投稿しました。formに値登録する仕組みは分かったのですが、では変更画面のような用途を想定して事前にformに値をセットするにはどうすれば良いかというのが今回の記事です。

対応

こちらのドキュメントにある通り、useFormを使った宣言部分でdefaultValuesを設定します。setValueでも値自体は設定できるのですが、Validationと連動しないので適切な値を入れた状態にしてもValidationの結果がfalseとなっている状態になります。

実装サンプル

IDと名前を入力する実装サンプルです。

sample.js
export default function UserRegisterComponent(prop) {
  const { register, handleSubmit, errors, formState, setValue } = useForm({
    mode: "onChange",
    defaultValues: {
      id: "initial_id",
      name: "初期値の名前",
    },
  });
  function submitData(data) {
    // submit以降の処理は割愛・・
  }

  return (
    <div>
      <Form onSubmit={handleSubmit(registerUser)}>
        <Form.Label>ユーザID</Form.Label>
        <Form.Control
          id="id"
          type="text"
          name="id"
          placeholder="ユーザID"
          isInvalid={errors.id}
          style={{ width: "300px" }}
          ref={register({
            required: "IDは入力必須です",
          })}
        />
        {errors.id && (
          <Form.Control.Feedback type="invalid">
            {errors.id.message}
          </Form.Control.Feedback>
        )}
        <br />
        <Form.Label>名前</Form.Label>
        <Form.Control
          id="name"
          type="text"
          name="name"
          placeholder="名前"
          isInvalid={errors.name}
          style={{ width: "300px" }}
          ref={register({
            required: "名前は入力必須です",
          })}
        />
        {errors.name && (
          <Form.Control.Feedback type="invalid">
            {errors.name.message}
          </Form.Control.Feedback>
        )}
      </Form>
    </div>
  };
}


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