Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show Error From Controllers in React Hook Forms

I am trying to throw required errors from my input which I have wrapped in a Controller component from react-hook-form version 7.

My Input is a Material-UI TextField as such;

<Controller
                        
    name="firstName"
    control={control}
    defaultValue=""
    rules={{ required: true}}
    render={({field}) =>
        <TextField
        id="firstName"
        name="firstName"
        autoComplete="fname"
        variant="outlined"
        fullWidth
        label="First Name"
        autoFocus={true}
        {...field} />
    }
/>

I would like to expose an error when rules fails.

like image 994
John Nyingi Avatar asked Mar 11 '26 12:03

John Nyingi


1 Answers

You need to pass the property of the errors object matching your field name to your Material UI <TextField />. The errors object is available via the formState property.

const {
    handleSubmit,
    control,
    formState: { errors }
  } = useForm();

You should also pass the ref to the inputRef prop instead of setting it to the ref prop. This will automatically focus the <TextField /> input if there is an error on submit.

<Controller
  name="firstName"
  control={control}
  defaultValue=""
  rules={{ required: true }}
  render={({ field: { ref, ...field } }) => (
    <TextField
      {...field}
      inputRef={ref}
      id="firstName"
      autoComplete="fname"
      variant="outlined"
      fullWidth
      error={!!errors.firstName}
      label="First Name"
    />
  )}
/>

Edit React Hook Form - MUI Autocomplete (forked)

like image 162
knoefel Avatar answered Mar 13 '26 01:03

knoefel