Show Error From Controllers in React Hook Forms

Viewed 5990

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.

2 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)

What @knoefel is saying is working. Something else you can do is using the fieldState. See official documentation here.

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

Then with error you would get the error object. So you could use {error?.message} to display the error message.

Related