Chase Dudas
Chase Dudas

Reputation: 104

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 || ''}
/>

Upvotes: 2

Views: 4603

Answers (2)

Abdeldjalil Hachimi
Abdeldjalil Hachimi

Reputation: 121

I think what you can do in this case

<Controller
          control={control}
          rules={{
            required: "Ceci c'est obligatoire.",
          }}
          name="value"
          render={({
            field: { ref, ...field }, <===
            fieldState: { invalid, error }, <===
          }) => (
            <TextField
              // ref={ref}
              id={field.name}
              inputRef={ref} <===
              {...field}
              error={invalid} <=== 
              helperText={error?.message} <===

looks simple as you can see I hope you find it useful

Upvotes: 0

Chase Dudas
Chase Dudas

Reputation: 104

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.

Upvotes: 2

Related Questions