Boon
Boon

Reputation: 1153

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;

Upvotes: 0

Views: 2673

Answers (1)

k0uh0t
k0uh0t

Reputation: 156

I think rules conflicts with required of TextField.

I confirmed it works. (https://codesandbox.io/s/practical-chebyshev-9twrle?file=/src/userForm.js)

<Controller
  name="title"
  control={control}
  rules={{ required: true }}
  render={({ field }) => {
    return (
      <TextField
        {...field}
        id="title"
        label="Title"
        error={Boolean(errors.title)}
        helperText={errors.title && "Title is required"}
      />
    );
  }}
/>

Also you don't have to wrap with Controller for such a simple case.

Example: https://codesandbox.io/s/practical-chebyshev-9twrle?file=/src/userFormWithoutController.js

Upvotes: 2

Related Questions