'Focus On Input With Error on Form Submission

It would be nice to have functionality when the user submits a form that fails the validation, it will set focus on the first field with an error.

I have shouldFocusError : true set in the useForm configuration. When I click submit, the validation triggers, but the input is not focused.

Any suggestions on how I can achieve this?

For reference, I am using MUI and react-hook-form to create custom components in the form. For the components themselves, they are using the useController hook like so:

const { field, fieldState } = useController(props);
<TextField
    {...field}
    error={!!fieldState.error}
    helperText={fieldState.error?.message || ''}
/>


Solution 1:[1]

Solution:

Spreading the field object returned from the useController hook contains the following:

{
    value: ...
    name: ...
    onChange: ...
    onBlur: ...
    ref: ...
}

The problem I described above was solved when I removed ref property from the object and passed it separately to inputRef. Like so:

const { field, fieldState } = useController(props);
const { ref, ...fieldProps } = field;
<TextField
    {...fieldProps}
    inputRef={ref} //or you can use field.ref
    id={field.name} //this solved other issues I was having
    error={!!fieldState.error}
    helperText={fieldState.error?.message || ''}
/>

After doing this, React Hook Form set focus on the first field with an error when the user submits a form that fails the validation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chase Dudas