Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally disable the submit button with react-hook-form?

Couldn't find a solution.
I'm using react-hook-form and I want to disable the submit button when the forms are empty and enable as long as all forms have atleast something written in them.
How would I do that using react-hook-form?

like image 718
Mr.Joony Avatar asked Dec 11 '20 16:12

Mr.Joony


3 Answers

The best solution I found so far using formState and by setting the mode to onChange.

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

And on the submit button:

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

Based on this issue: https://github.com/react-hook-form/react-hook-form/issues/77

onChange mode explanation from the documentation:

Validation will trigger on the change event with each input, and lead to multiple re-renders. Warning: this often comes with a significant impact on performance.

like image 115
Guilherme Akira Matsumoto Avatar answered Oct 13 '22 03:10

Guilherme Akira Matsumoto


const { 
    register, 
    handleSubmit, 
    formState: { isSubmitting, isDirty, isValid } // here
  } = useForm({ mode: "onChange" })


<button
  type="submit"
  disabled={!isDirty || !isValid} // here
>
  Comment
</button>
like image 24
Joshua Galit Avatar answered Oct 13 '22 04:10

Joshua Galit


you can use formState => isDirty which means form is been modified.

https://react-hook-form.com/api#formState

here is a working example for formState below:

https://codesandbox.io/s/react-hook-form-v6-formstate-ht098?file=/src/index.jsx:423-432

<input disable={formState.isDirty} type="submit" />

like image 2
Bill Avatar answered Oct 13 '22 03:10

Bill