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

Viewed 29265

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?

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


<button
  type="submit"
  disabled={!isDirty || !isValid} // here
>
  Comment
</button>

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.

Close but I think the logic is slightly off from the other comments. The key is to use the && operator. Credit to the example with the Formik library.

const { formState: { errors, isDirty, isValid } } = useForm()
///...
<button type="submit" disabled={!isDirty && !isValid}>
Continue
</button>
Related