rjc30
rjc30

Reputation: 247

undefined errors object in react-hook-form

I'm having this issue of

Cannot read property 'title' of undefined.

I already follow the sample code on the documentation of react-hook-form but I'm still having this issue.

const [taskInfo, setTaskInfo] = useState({
    title: '',
    description: '',
    created: currentUser.fullname,
    assigned: '',
    priority: '',
    dateDue: new Date(),
  });


const handleChange = (e) => {
    const { name, value } = e.target;
    setTaskInfo((prev) => ({ ...prev, [name]: value }));
  };


const { register, errors, handleSubmit } = useForm();

<TextField
  fullWidth
  variant='outlined'
  label='Title'
  value={taskInfo.title}
  onChange={handleChange}
  onFocus={handleDisbleLabel}
  onBlur={handleEnableLabel}
  InputLabelProps={{ shrink: false }}
  {...register('title', { required: 'This is required' })}
/>
  {errors.title && 'Your input is required'}

Upvotes: 4

Views: 8839

Answers (1)

NearHuscarl
NearHuscarl

Reputation: 81310

If you are using react-hook-form v7, the errors object is moved to formState now, change your code to:

const { register, formState: { errors }, handleSubmit } = useForm();

Instead of

const { register, errors } = useForm();

Reference: migrate-v6-to-v7.

Upvotes: 20

Related Questions