Transitioning to React Hook Form from Formik while incorporating Material UI V5 and yup for validation poses a current challenge.
There are two key issues I am addressing:
- Encountering TS Errors related to various RHF props and options.
- Desiring validation on both onBlur and onSubmit, but currently only seeing HTML5 validation display onSubmit.
Below is the code snippet:
import { useForm, Controller } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import {
Box,
Button,
CircularProgress,
Grid,
InputAdornment,
TextField,
Theme,
Typography,
useMediaQuery,
} from '@mui/material';
import { validationSchema } from './validationSchema'
const LoginForm: React.FC = () => {
const {
control,
handleSubmit,
formState: { errors },
} = useForm({
resolver: yupResolver(validationSchema),
mode: 'onBlur',
reValidateMode: 'onChange',
defaultValues: {
email: '',
password: '',
},
});
const handleSignin = async (credentials: Values) => {
// Logic for sign in here
};
return (
<BoxContainer>
<form onSubmit={handleSubmit(handleSignin)}>
<Grid container spacing={2}>
<Grid item xs={12}>
<Controller
name="email"
control={control}
render={({ field }) => (
<TextField
{...field}
error={!!errors?.email}
helperText={errors?.email?.message}
size="small"
autoFocus
label="Email"
fullWidth
autoComplete="email"
type="email"
variant="outlined"
InputProps={{
startAdornment: (
<InputAdornment position="start">
<EmailIcon />
</InputAdornment>
),
}}
/>
)}
/>
</Grid>
// Other grid items and components...
</Grid>
</form>
</BoxContainer>
);
}
The flagged TS errors have been marked alongside the problematic code snippets.
The secondary issue arises when an invalid or empty email input transitions between focus states resulting in differing error feedback. Ideally, I aim for combined onBlur and onSubmit validation modes.
Thus far, React Hook Form exhibits promise, with ongoing refinement of errors and functionality.