import React from"react";import{ useForm }from"react-hook-form";exportdefaultfunctionApp(){const{ register, handleSubmit, watch,formState:{ errors }}=useForm();constonSubmit=data=> console.log(data);
console.log(watch("example"));// watch input value by passing the name of itreturn(/* "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>);}
♦
React Web Video Tutorial
This video tutorial illustrates the basic usage and concepts of React Hook Form.
Register fields
One of the key concepts in React Hook Form is to register your component into the hook. This will make its value available for both the form validation and submission.
Note: Each field is required to have a name as a key for the registration process.
import React from"react";import{ useForm }from"react-hook-form";// The following component is an example of your existing Input ComponentconstInput=({ label, register, required })=>(<><label>{label}</label><input {...register(label,{ required })}/></>);// you can use React.forwardRef to pass the ref tooconst Select = React.forwardRef(({ onChange, onBlur, name, label }, ref)=>(<><label>{label}</label><select name={name} ref={ref} onChange={onChange} onBlur={onBlur}><option value="20">20</option><option value="30">30</option></select></>));exportdefaultfunctionApp(){const{ register, handleSubmit }=useForm();constonSubmit=(data)=>{alert(JSON.stringify(data));};return(<form onSubmit={handleSubmit(onSubmit)}><Input label="First Name" register={register} required /><Select label="Age"{...register("Age")}/><input type="submit"/></form>);};
Integrating with UI libraries
React Hook Form has made it easy to integrate with external UI component libraries. If the component doesn't expose input's ref, then you should use the Controller component, which will take care of the registration process.
This library embraces uncontrolled components and native HTML inputs, however, it's hard to avoid working with external controlled components such as React-Select, AntD and Material-UI. To make this simple, we provide a wrapper component: Controller to streamline the integration process while still giving you the freedom to use a custom register.
import React from"react";import{ TextField }from"@material-ui/core";import{ useController, useForm }from"react-hook-form";functionInput({ control, name }){const{ control }=useForm();const{field:{ onChange, onBlur, name, value, ref },fieldState:{ invalid, isTouched, isDirty },formState:{ touchedFields, dirtyFields }}=useController({
name,
control,rules:{required:true},defaultValue:"",});return(<TextField
onChange={onChange}// send value to hook form
onBlur={onBlur}// notify when input is touched/blur
value={value}// input value
name={name}// send down the input name
inputRef={ref}// send input ref, so we can focus on input when error appear/>);}
Integrating with global state
It doesn't require you to rely on a state management library, but you can easily integrate with them.
import React from"react";import{ useForm }from"react-hook-form";import{ connect }from"react-redux";import updateAction from"./actions";exportdefaultfunctionApp(props){const{ register, handleSubmit, setValue }=useForm();// Submit your data into Redux storeconstonSubmit=data=> props.updateAction(data);return(<form onSubmit={handleSubmit(onSubmit)}><Input {...register("firstName")} defaultValue={props.firstName}/><Input {...register("lastName")} defaultValue={props.lastName}/><input type="submit"/></form>);}// Connect your component with reduxconnect(({ firstName, lastName })=>({ firstName, lastName }), updateAction)(YourForm);
Handle errors
React Hook Form provides an errors object to show you the errors in the form. errors's type will return given validation constraints. The following example showcases a required validation rule.
import React from"react";import{ useForm }from"react-hook-form";constonSubmit=data=> console.log(data);exportdefaultfunctionApp(){const{ register,formState:{ errors }, handleSubmit }=useForm();return(<form onSubmit={handleSubmit(onSubmit)}><input {...register("firstName",{required:true})}/>{errors.firstName?.type ==='required'&&"First name is required"}<input {...register("lastName",{required:true})}/>{errors.lastName &&"Last name is required"}<input type="submit"/></form>);}
Schema Validation
We also support schema-based form validation with Yup, Zod , Superstruct & Joi, where you can pass your schema to useForm as an optional config. It will validate your input data against the schema and return with either errors or a valid result.
Step 1: Install Yup into your project.
npm install @hookform/resolvers yup
Step 2: Prepare your schema for validation and register inputs with React Hook Form.