How to use React Hook Form with Validation

0

 

Form handling in React is much easier already, you can just use hooks and you are good to go. But, it can get complicated once your form grows extensively.

Hook like useState, is a good choice if the form has only a few inputs and the data is just some text fields. If your form has dozens of inputs, and different types of inputs, I think you should avoid using just Hooks.

Hooks can cause multiple re-rendering and may cause data loss. Also, the code can get messier. From a performance point of view, it’s not suggested to use hooks to handle large forms.

So, to avoid these issues, there are already a couple of third-party Form libraries which make handling forms much easier. But today we’ll use React Hook Form.

React Hook Form is a library to handle forms in React. React Hook Form is pretty lightweight, clean and with high performance is one of the best form libraries out there. Not only that, but it also has one of the easiest validations I’ve ever seen.

So, let’s see it in action.

#1 Install & Initialize React Hook Form –

I hope you’ve already set up a new React app, if you haven’t just head over to the Codesandbox.io, and open a new React app with just a single click.

Now, install the library with the below command,

Terminal
npm install react-hook-form #or yarn add react-hook-form

After installation is completed, let’s initialize it,

App.jsx
import { useForm } from "react-hook-form"; export default function App() { const {register, handleSubmit} = useForm(); return ( <div className="app"> <h2>React Hook Form</h2> </div> ); }

React Hook Form uses hooks behind the scenes, so the syntax is similar. The register, and handleSubmit, are two fixed state methods, the first one is an object and the second is a function just like useState.

There is one more state method, but we’ll see them later.

#2 Handling Form Fields –

App.jsx
<div className="App"> <h1>React Hook Form Tutorial</h1> <form onSubmit={handleSubmit(onSubmit)}> <label htmlFor="name"> Name: <br /> <input {...register("name", { required: true })} type="text" /> <br /> </label> <label htmlFor="email"> Email: <br /> <input {...register("email", { required: true })} type="email" /> <br /> </label> <label htmlFor="username"> Username: <br /> <input {...register("username", { required: true, maxLength: 30 })} type="text" /> <br /> </label> <label htmlFor="password"> Password: <br /> <input {...register("password", { required: true, maxLength: 8 })} type="password" /> <br /> </label> <button type="submit">Register</button> </form> </div>

I’ve created a pretty simple HTML form. The way we handle input here is pretty much easier than using the normal state.

Just inside the input element, spread the registerobject, which is also the initial state, and here it takes two parameters. The first is key, for the object and the second is the validation.

As you can see, how simpler and clean it is to handle inputs using React Hook Form. Now, let’s handle the data.

#3 Handling Form Data –

You might have noticed that I’ve used onSubmit, function inside the handleSubmit, function. It’s the way this library works.

So, we need to create the onSubmit, function and it will receive the form data as the parameter.

App.jsx
import { useForm } from "react-hook-form"; export default function App() { const {register, handleSubmit} = useForm(); const onSubmit = (data) => { console.log(data); }; return ( <div className="App"> <h1>React Hook Form Tutorial</h1> <form onSubmit={handleSubmit(onSubmit)}> <label htmlFor="name"> Name: <br /> <input {...register("name", { required: true })} type="text" /> <br /> </label> <label htmlFor="email"> Email: <br /> <input {...register("email", { required: true })} type="email" /> <br /> </label> <label htmlFor="username"> Username: <br /> <input {...register("username", { required: true, maxLength: 30 })} type="text" /> <br /> </label> <label htmlFor="password"> Password: <br /> <input {...register("password", { required: true, maxLength: 8 })} type="password" /> <br /> </label> <button type="submit">Register</button> </form> </div> ); }

If you check your console after submitting the form you might get something like this.

React Hook Form Tutorial for Beginners

Now, you can set this data as a state, or send it to the backend.

Also, check out,
How to handle APIs in React using Axios

#4 Let’s do some Validation Check –

Applying the validation and error checking is just a cup of tea. You just need to grab an extra method for useForm().

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

We’ve already added some validations like required and max length, etc. The errors, object get’s all of that information and is updated whenever we update our input field so it’s pretty fast.

let’s use it in action.

App.jsx
return ( <div className="App"> <h1>React Hook Form Tutorial</h1> <form onSubmit={handleSubmit(onSubmit)}> <label htmlFor="name"> Name: <br /> <input {...register("name", { required: true })} type="text" /> <br /> {errors.name?.type === "required" && <p>*name is required</p>} </label> <label htmlFor="email"> Email: <br /> <input {...register("email", { required: true })} type="email" /> <br /> {errors.email?.type === "required" && <p>*email is required</p>} </label> <label htmlFor="username"> Username: <br /> <input {...register("username", { required: true, maxLength: 30 })} type="text" /> <br /> {errors.username?.type === "required" && <p>*username is required</p>} </label> <label htmlFor="password"> Password: <br /> <input {...register("password", { required: true, maxLength: 8 })} type="password" /> <br /> {errors.password?.type === "required" && <p>*password is required</p>} </label> <button type="submit">Register</button> </form> </div> ); }

Just below the input fields, we’ll add a quick one-line error-checking thanks to the ES6. As you can guess errors, is an object with password, as a key with another nested key-value pair type.

As you can see, to avoid undefined errors, we are using optional chaining errors.password?.type, the question mark will make sure to wait till the password has some input data before deciding on validation.

React Hook Form with Error Validations

Source Code –

  • Github
  • Codesandbox.io

Conclusion –

It’s not necessary to use React Hook Form for all of your projects, it depends on the type of form you are trying to handle. But, in most cases using this library is not only going to keep your codebase clean but also save your time debugging the code.


Post a Comment

0Comments
Post a Comment (0)
To Top