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.
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"
/>
)}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With