'React Hook Form & Material UI: errors are undefined
I'm using React Hook Form v7 with Material UI v5. I have a simple form component as shown below. I have marked the TextField as required, however, the error state and helper text are never shown when the value of the field is empty. The value of errors.title is always undefined.
What am I doing wrong here? How can I get the React Hook Form validation working, i.e. errors?
import React from 'react';
import Grid from '@mui/material/Grid';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import { useForm, Controller } from 'react-hook-form';
import backEndApi from '../api/backEndApi';
const UserForm = function () {
const { control, handleSubmit, formState: { errors }, getValues } = useForm();
const onFormSubmit = (event) => {
event.preventDefault();
backEndApi.post(getValues());
};
return (
<Grid container alignItems="center" justify="center" direction="column" paddingTop="10%">
<form onSubmit={handleSubmit(onFormSubmit)}>
<Grid container alignItems="center" justify="center" direction="column" spacing={5}>
<Grid item>
<Controller
name="title"
control={control}
rules={{ required: true }}
render={({ field }) => {
return (
<TextField
{...field}
id="title"
label="Title"
required
error={errors.title}
helperText={errors.title && 'Title is required'}
/>
);
}}
/>
</Grid>
<Grid item>
<Button id="job-submit" color="primary" type="submit" variant="contained">
Create Job
</Button>
</Grid>
</Grid>
</form>
</Grid>
);
};
export default UserForm;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
