'React Form hook - getting "required field" error message despite input being entered
I just started building a form using react form hook. Just started with single input called name and when I submit the form I get the error message.
I tried to follow these instructions: https://react-hook-form.com/get-started
//I have tried with this but I get unexpected token error:
<input {...register('name', { required: true })} />
import React from 'react'
import { useForm } from 'react-hook-form'
const NewUserForm = () => {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = data => console.log(data)
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input type="text" placeholder="Name" name="name" ref={register('name', {required: true})} />
{errors.name && <span> This field is required</span>}
<input type="text" placeholder="Email" name="email" ref={register('email', {required: true})} />
{errors.email && <span> This field is required</span>}
<input type="submit" />
</form>
)
}
export default NewUserForm
Solution 1:[1]
Have you tried optional chaining the errors?
errors?.email?.message
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Joe Avila |