1
votes

I am trying to use ChakraUI and React-Hook-Form to create my form. However, my errors are not working. I have tried not using chakra ui but still it does not work. Here is my code:

import React from 'react'
import { useForm } from "react-hook-form";
import "./App.css"
import { Input } from "@chakra-ui/react"
import { Text } from "@chakra-ui/react"
import {
    Alert,
    AlertIcon,
    AlertTitle,
    AlertDescription,
} from "@chakra-ui/react"


function App() {

    const { register, handleSubmit, errors } = useForm();
    const onSubmit = data => console.log(data);

    return (
        <div className="app-container">
            <form onSubmit={handleSubmit(onSubmit)}>
                <div className="header-container">
                    <Text fontSize="3xl" align="center" className="app-header">Finish the survey</Text>
                </div>
                <div className="email">
                    <Text fontSize="xl">Your Email</Text>
                    <Input name="email" placeholder="Your Email..." type="text" ref={register({ maxLength: { value: 23, message: "test" } })} />
                    {errors.email && (<span>{errors.email.message}</span>)}
                </div>
            </form>
        </div>
    )
}

export default App
1
There is no issue with your code. It's working and the errors are populating. By default react-hook-form only validates on submission of the form. So press enter after typing and you'll see it. You can change this behavior by modifying your useForm variables ` const { register, handleSubmit, errors } = useForm({ mode: 'onChange', reValidateMode: 'onChange' });` - Rykuno

1 Answers

2
votes

Without knowing the version of the library you are using, I can't say for certain, but try changing

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

to

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

I ran into the same problem when following their example off of the home page of the library's website and have since put in a PR.