4

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'}
1
  • Where is taskInfo defined? Commented Apr 21, 2021 at 12:15

1 Answer 1

20

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you so much sir! I overlook the link of the documentation that i'm reading, it's for version 6 not version 7.
Sir, how can solve the issue in terms of onChange? I can't type anything on the text field. Because I need to insert the name attribute but after inserting the attribute the issue still remains.
@rjc30 Sorry, somehow I missed your first comment, you need to pass the ref to inputRef props of TextField. See this, it's the same problem except the author uses v7.
@rjc30 are you using react-hook-form v7 or v6. Because the code in your question ...register() is from v7. Also why do you need to control the form value by calling setState(), react-hook-form handles that for you internally, if you want to access the form values, use getValues() method instead.
@rjc30 Here is a tip: you will get help a lot quicker from other people if you can provide a demo (codepen, codesandbox...) in your question. The live example from react-hook-form docs uses codesandbox so you may want to fork it and reproduce your problem.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.