Alex Cotton
Alex Cotton

Reputation: 101

React Hook Form doesn´t display errors (TypeError: Cannot read properties of undefined (reading 'name')

I have a React hook Form v7 and it doesn´t seem to recognize the error messages, the error I get is as follows: TypeError: Cannot read properties of undefined (reading 'name') for every input field.

I believe it doesn´t know what field im refering to, but I have set the name of each field and but that still doesn´t fix the problem.

** Im using NextJS and TailwindCSS

This is the code for my Form:

import React from 'react'
import { useForm, Controller } from 'react-hook-form'
import { Checkbox } from "@material-ui/core";

function ContactForm() {
    const {register, handleSubmit, errors, reset } = useForm();
    function onSubmitForm(values) {
        console.log(values);
    }
    
  return (
    <div className='my-6 max-w-screen-lg mx-auto'>
        <form onSubmit={handleSubmit(onSubmitForm)}>


            {/* Name input field */}

            <div className='flex flex-col'>
                <label for='name' className='mb-2'>
                    Nombre
                </label>
                <input
                    type="text"
                    name="name"
                    className=" rounded-sm bg-black border-2 mb-4 p-1"
                    {...register("name", { required: true, message: "Campo obligatorio"}) }
                />
                {errors.name && <span className='text-danger'>{errors.name.message}</span>}
            </div>

            {/* Surname input field */}

            <div className='flex flex-col'>
                <label for='surname' className='mb-2'>
                    Apellido
                </label>
                <input
                    type="text"
                    name="surname"
                    className=" rounded-sm bg-black border-2 mb-4 p-1"            
                    {...register("surname", { required: true, message: "Campo obligatorio"}) }
                />
                {errors.surname && <span className='text-danger'>{errors.surname.message}</span>}
            </div>

            {/* companyName input field */}

            <div className='flex flex-col'>
                <label for='companyName' className='mb-2'>
                    Nombre de la empresa
                </label>
                <input
                    type="text"
                    name="companyName"
                    className=" rounded-sm bg-black border-2 mb-4 p-1"
                    {...register('companyName', { required: true, message: "Campo obligatorio"}) }
                />
                {errors.companyName && <span className='text-danger'>{errors.companyName.message}</span>}
            </div>

            {/* Email input field */}

            <div className='flex flex-col'>
                <label for='email' className='mb-2'>
                    Email
                </label>
                <input 
                    type="email"
                    name="email"
                    className=" rounded-sm bg-black border-2 mb-4 p-1"
                    {...register("email", { required: {value: true, message: "Campo obligatorio"}, pattern: { value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
                    message: "El formato no es correcto" } }) }
                />
                {errors.email && <span className='text-danger'>{errors.email.message}</span>}
            </div>

            {/* Number of employees input field */}

            <div className='flex flex-col'>
                <label for='numberOfEmployees' className='mb-2'>
                    Número de empleados
                </label>
                <select className=" rounded-sm bg-black border-2 mb-4 p-1">
                    <option value='1-5'>1-5</option>
                    <option value='5-25'>5-25</option>
                    <option value='+25'>+25</option>
                </select>
            </div>

            {/* Aditional info textarea input field */}

            <div className='flex flex-col'>
                <label for='message' className='mb-2'>
                    Cuéntanos más detalles
                </label>
                <textarea 
                    name="info"
                    rows="4"
                    className=" rounded-sm bg-black border-2 mb-4 p-1"
                    placeholder="Háblanos sobre lo que necesitas, tus objectivos y presupuesto"
                    {...register('info', { required: true, message: "Campo obligatorio"}) }
                />
                {errors.info && <span className='text-danger'>{errors.info.message}</span>}
            </div>

            {/* Information */}

            <div>
                <p className='text-xs sm:text-sm text-gray-400 mb-4'>COTTONMEDIA tratará sus datos personales para dar respuesta a las solicitudes planteadas. Puede ejercer sus derechos de acceso, supresión y portabilidad de sus datos, de limitación y oposición a su tratamiento, así como a no ser objeto de decisiones basadas en el tratamiento automatizado de sus datos, cuando procedan, en la dirrección de correo electrónico [email protected]</p>
            </div>

            {/* Consent checkbox field */}

            <div>
                <Checkbox>

                </Checkbox>
                He leido, entiendo y acepto la <a href='/politica-de-privacidad' className='underline'>Política de privacidad</a> y la <a href='/politica-de-cookies' className='underline'>Política de cookies</a>.
            </div>


            {/* submit button */}

            <div>
                <button type='submit' className='bg-slate-400 rounded-sm mt-6 w-20 p-1'>
                    Enviar
                </button>
            </div>

        </form>
    </div>
  )
}

export default ContactForm

Upvotes: 1

Views: 2543

Answers (1)

Ricardo
Ricardo

Reputation: 96

As the react-hook-form documentation states, the errors object is available inside the form state. So instead, you could do something like this:

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

Upvotes: 3

Related Questions