React 18

Last Updated: 10/27/2023

React Hook Form

  • As your forms get more complex, managing the form state with a state hook can become time consuming and error prone. For every input field, you have to set to attributes onChange and value.
  • You can use a popular library called react hook form. With this library, you can quickly build forms with less code.

Code

  • Install
npm i react-hook-form@7.43
  • Import
import {useForm} from "react-hook-form";
  • Call useForm
const {register, handleSubmit} = useForm();
  • Register Control
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("name")} />
<input {...register("age")} />
</form>
  • Pass submit handler
onSubmit = (data:FieldValues) => console.log(data);