Education
Developer Advocate
Last updated on Sep 15, 2023
Last updated on Aug 8, 2023
React has revolutionized the way we build user interfaces, and with the introduction of hooks, it has become even more powerful. Among the various hooks available, the React Hook Form stands out as a superb tool for handling form validation and state management. Thanks to author Bill Luo aka @bluebill1049.
React Hook Form is a minimalistic library that simplifies the process of creating forms in React. It leverages the power of React Hooks to provide a better form validation strategy. It's lightweight, easy to use, and highly efficient, making it a go-to choice for many developers.
In this blog post, we will delve deep into the world of React Hook Form. We will explore how to use it, its key features, and how it can help you create robust forms with ease. We will also look at some code snippets to get a better understanding of its practical applications.
This article assumes that you are familiar with React and its hooks. If you're new to React, I recommend starting with the official React documentation.
So, let's dive in and explore the power of React Hook Form!
Getting Started with React Hook Form
To kick things off, you need to install React Hook Form in your project. You can do this using npm or yarn. Here's how to do it with npm:
1 npm install react-hook-form 2
Once you've installed React Hook Form, you can import it into your component like this:
1 import { useForm } from 'react-hook-form'; 2
Now that we have React Hook Form installed, let's create a simple form. We'll start with a basic form with a single input field for the user's name.
1 import React from 'react'; 2 import { useForm } from 'react-hook-form'; 3 4 function App() { 5 const { register, handleSubmit } = useForm(); 6 const onSubmit = data => console.log(data); 7 8 return ( 9 <form onSubmit={handleSubmit(onSubmit)}> 10 <input name="name" ref={register} /> 11 <input type="submit" /> 12 </form> 13 ); 14 } 15 16 export default App; 17
In the above code, we're using the useForm hook from React Hook Form. This hook returns an object with methods that you can use to work with the form. The register function is used to register an input field with the form. The handleSubmit function is used to handle the form submission.
When the form is submitted, the onSubmit function is called with the form data. In this case, we're just logging the data to the console, but in a real application, you would typically send this data to a server.
Form Validation with React Hook Form
One of the key features of React Hook Form is its support for form validation. Let's see how we can add some validation rules to our form.
1 import React from 'react'; 2 import { useForm } from 'react-hook-form'; 3 4 function App() { 5 const { register, handleSubmit, errors } = useForm(); 6 const onSubmit = data => console.log(data); 7 8 return ( 9 <form onSubmit={handleSubmit(onSubmit)}> 10 <input name="name" ref={register({ required: true })} /> 11 {errors.name && <p>Name is required</p>} 12 <input type="submit" /> 13 </form> 14 ); 15 } 16 17 export default App; 18
In the above code, we're passing an object to the register function with a required property. This tells React Hook Form that the name field is required. If the user tries to submit the form without entering a name, the form will not be submitted, and an error message will be displayed.
The errors object contains any validation errors for the form. We can use this object to display error messages to the user. In this case, we're displaying a simple "Name is required" message if the name field is empty.
So far, we've only worked with a single input field. But in most cases, you'll have multiple input fields in your form. Let's see how we can handle multiple input fields with React Hook Form.
1 import React from 'react'; 2 import { useForm } from 'react-hook-form'; 3 4 function App() { 5 const { register, handleSubmit, errors } = useForm(); 6 const onSubmit = data => console.log(data); 7 8 return ( 9 <form onSubmit={handleSubmit(onSubmit)}> 10 <input name="firstName" ref={register({ required: true })} /> 11 {errors.firstName && <p>First name is required</p>} 12 <input name="lastName" ref={register({ required: true })} /> 13 {errors.lastName && <p>Last name is required</p>} 14 <input type="submit" /> 15 </form> 16 ); 17 } 18 19 export default App; 20
In the above code, we've added a second input field for the user's last name. We're registering this field with the form and adding a validation rule just like we did for the first name field. We're also displaying an error message if the last name field is empty.
This is just the tip of the iceberg when it comes to what you can do with React Hook Form. It supports a wide range of validation rules, and you can even create your own custom validation rules if you need to. It also provides a number of other features, such as form state management, form arrays, and more.
Now that we've covered the basics, let's dive a little deeper into some of the more advanced features of React Hook Form.
Form arrays are a common requirement in many applications. They allow you to manage a collection of form fields that can be dynamically added or removed. React Hook Form makes it easy to work with form arrays using the useFieldArray hook.
Here's an example of how you can create a form array with React Hook Form:
1 import React from 'react'; 2 import { useForm, useFieldArray } from 'react-hook-form'; 3 4 function App() { 5 const { register, control, handleSubmit } = useForm(); 6 const { fields, append, remove } = useFieldArray({ 7 control, 8 name: 'names' 9 }); 10 const onSubmit = data => console.log(data); 11 12 return ( 13 <form onSubmit={handleSubmit(onSubmit)}> 14 {fields.map((field, index) => ( 15 <div key={field.id}> 16 <input 17 name={`names[${index}].name`} 18 ref={register()} 19 defaultValue={field.name} 20 /> 21 <button type="button" onClick={() => remove(index)}> 22 Remove 23 </button> 24 </div> 25 ))} 26 <button type="button" onClick={() => append({ name: '' })}> 27 Add 28 </button> 29 <input type="submit" /> 30 </form> 31 ); 32 } 33 34 export default App; 35
In the above code, we're using the useFieldArray hook to manage an array of name fields. The fields array contains the current state of the form array. The append function is used to add a new field to the array, and the remove function is used to remove a field from the array.
React Hook Form supports a wide range of validation rules out of the box, but sometimes you might need to create your own custom validation rules. You can do this by passing a function to the register method.
Here's an example of how you can create a custom validation rule:
1 import React from 'react'; 2 import { useForm } from 'react-hook-form'; 3 4 function App() { 5 const { register, handleSubmit, errors } = useForm(); 6 const onSubmit = data => console.log(data); 7 8 return ( 9 <form onSubmit={handleSubmit(onSubmit)}> 10 <input 11 name="age" 12 ref={register({ 13 validate: value => value >= 18 || 'You must be at least 18 years old' 14 })} 15 /> 16 {errors.age && <p>{errors.age.message}</p>} 17 <input type="submit" /> 18 </form> 19 ); 20 } 21 22 export default App; 23
In the above code, we're creating a custom validation rule for the age field. The validation function checks if the value is 18 or greater. If it's not, it returns an error message.
React Hook Form works well with third-party UI libraries. You can use the Controller component to wrap third-party form controls and integrate them with React Hook Form.
Here's an example of how you can integrate React Hook Form with a third-party UI library:
In the above code, we're using the Controller component to wrap a Select component from the react-select library. The Controller component takes care of registering the component with the form and handling its value changes.
As a React developer, you're likely always on the lookout for tools and resources that can make your life easier. One such tool is WiseGPT, a generative AI designed specifically for React developers. It can help you write code in your style without context limit, and it even provides API integration by accepting Postman collections. It's also supported in the VSCode itself, making it a handy tool to have in your development arsenal. It's like having a pair of extra hands when you're coding, especially when you're working with complex forms using React Hook Form.
Once you've set up your form with React Hook Form, the next step is to handle form submission. React Hook Form makes this process straightforward and intuitive.
Here's how you can handle form submission with React Hook Form:
1 import React from 'react'; 2 import { useForm } from 'react-hook-form'; 3 4 function App() { 5 const { register, handleSubmit } = useForm(); 6 const onSubmit = data => console.log(data); 7 8 return ( 9 <form onSubmit={handleSubmit(onSubmit)}> 10 <input name="name" ref={register({ required: true })} /> 11 <input type="submit" /> 12 </form> 13 ); 14 } 15 16 export default App; 17
In the above code, we're using the handleSubmit function from React Hook Form to handle form submission. The handleSubmit function takes a callback function as its argument. This callback function is called when the form is submitted, and it receives the form data as its argument.
React Hook Form provides robust support for error handling. It exposes an errors object that contains any validation errors for the form.
Here's how you can display validation error messages with React Hook Form:
1 import React from 'react'; 2 import { useForm } from 'react-hook-form'; 3 4 function App() { 5 const { register, handleSubmit, errors } = useForm(); 6 const onSubmit = data => console.log(data); 7 8 return ( 9 <form onSubmit={handleSubmit(onSubmit)}> 10 <input name="name" ref={register({ required: true })} /> 11 {errors.name && <p>Name is required</p>} 12 <input type="submit" /> 13 </form> 14 ); 15 } 16 17 export default App; 18
In the above code, we're checking if there's an error for the name field in the errors object. If there is, we're displaying an error message.
React Hook Form is a powerful library that simplifies the process of creating and managing forms in React. It provides a wide range of features, such as form validation, form arrays, and integration with third-party libraries. It's lightweight, easy to use, and highly efficient, making it a great choice for any React developer.
Whether you're building a simple contact form or a complex multi-step form, React Hook Form has got you covered. And with tools like WiseGPT to assist you, building forms in React has never been easier.
So, what are you waiting for? Give React Hook Form a try and see how it can improve your React development experience. Happy coding!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.