2
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?

More than 1 year has passed since last update.

react-hook-formでsubmitボタンを条件付きで無効にするには?

Posted at

formStateを使用し、モードをonChangeに設定すること

 const { register, handleSubmit, formState } = useForm({
    mode: "onChange"
  });

そして送信ボタンを以下のようにすること

<button disabled={!formState.isValid}/>

const OtherForms: React.FC<{}> = () => {
  const { register, handleSubmit, errors, formState } = useForm<FormData>({
    mode: 'onChange'
  });

  const onSubmit = (data: FormData): void => console.log(data);

  return (
    <div>
      <h2>タイトル名</h2>
      <form onSubmit={handleSubmit(onSubmit)}>
        <textarea
          name='title'
          ref={register({ required: true, maxLength: 20 })}
        />
        {errors.title && '作者名は1文字以上、20文字以下でなければなりません。'}
        <h2>作者名</h2>
        <textarea
          name='author'
          ref={register({ required: true, maxLength: 20 })}
        />
        {errors.author && '作者名は1文字以上、20文字以下でなければなりません。'}
        <button disabled={!formState.isValid}>送信する</button>
      </form>
    </div>
  );
};

export default OtherForms;
2
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
2
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?