5

I am trying to display an error message when nothing is typed inside the message input form, but when I load the page I get this error 'TypeError: Cannot read property 'message' of undefined'. I am using react-hook-forms. This is my code down below.

import { Button } from "@material-ui/core";
import { Close } from "@material-ui/icons";
import React from "react";
import { useForm } from "react-hook-form";
import "./SendMail.css";

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

  const onSubmit = (formData) =>{
    console.log(formData)
  }


  return (
    <div className="sendMail">
      <div className="sendMail__header">
        <h3>New Message</h3>
        <Close className="sendMail__close" />
      </div>
      <form onSubmit={handleSubmit(onSubmit)}>
        <input name='to' placeholder="To" type="text" {...register('to',{required:true})}/>
        
        <input name="subject" placeholder="Subject" type="text" {...register('subject',{required:true})} />
        
        <input
          name="message"
          placeholder="Message..."
          type="text"
          className="sendMail__message"
          {...register('message',{required:true})}
        />
        {errors.message && <p>To is required!!</p>}

        <div className="sendMail__send">
          <Button
            className="sendMail__send"
            variant="contained"
            color="primary"
            type="submit"
          >
            Send
          </Button>
        </div>
      </form>
    </div>
  );
};

export default SendMail;
2
  • Which version of react-hook-form do you use? Commented May 11, 2021 at 11:37
  • I am using 7.5.2 Commented May 11, 2021 at 11:42

1 Answer 1

7

Since v7 the errors object moved to the formState property, so you need to adjust your destructering:

const { register, handleSubmit, watch, formState: { errors } } = useForm();
Sign up to request clarification or add additional context in comments.

Comments

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.