I am trying to use react form hook. But it throws error.
import React, { useRef } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { useForm } from "react-hook-form"
export default function App() {
const {
register,
handleSubmit,
watch,
formState: { errors },
} = useForm()
const onSubmit = (data) => console.log(data)
console.log(watch("example")) // watch input value by passing the name of it
return (
/* "handleSubmit" will validate your inputs before invoking "onSubmit" */
<form onSubmit={handleSubmit(onSubmit)}>
{/* register your input into the hook by invoking the "register" function */}
<input defaultValue="test" {...register("example")} />
{/* include validation with required or other standard HTML validation rules */}
<input {...register("exampleRequired", { required: true })} />
{/* errors will return when field validation fails */}
{errors.exampleRequired && <span>This field is required</span>}
<input type="submit" />
</form>
)
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
JSON
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-hook-form": "^7.24.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
I tried to use a react form hook to use simple form. But it throws below error Cannot read properties of null (reading 'useRef') TypeError: Cannot read properties of null (reading 'useRef')