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.
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.
Share Improve this question edited May 22, 2021 at 11:21 John Nyingi asked May 22, 2021 at 11:02 John NyingiJohn Nyingi 1,1101 gold badge22 silver badges39 bronze badges2 Answers
Reset to default 14You 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"
/>
)}
/>
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.