React hook form library tutorial with examples

 

React Hook Form Tutorial with Examples

React Hook Form is a popular library for handling forms in React. It provides a simple and efficient way to manage form state, validation, and submissions using React hooks. It’s lightweight, flexible, and helps in reducing re-renders, making it faster than traditional form handling techniques.

In this tutorial, we will explore how to set up and use React Hook Form with various examples, including handling form validation, errors, and submitting data.


1. Installation

To get started with React Hook Form, you need to install it in your project.

npm install react-hook-form

2. Basic Example

Let's start with a simple form that takes the user's name and email and displays the submitted values.

App.js


import React from "react"; import { useForm } from "react-hook-form"; function App() { // useForm hook for form handling const { register, handleSubmit, formState: { errors } } = useForm(); // Handle form submission const onSubmit = (data) => { console.log("Form Data:", data); }; return ( <div className="App"> <h1>React Hook Form Example</h1> <form onSubmit={handleSubmit(onSubmit)}> <div> <label>Name:</label> <input type="text" {...register("name", { required: "Name is required" })} /> {errors.name && <span>{errors.name.message}</span>} </div> <div> <label>Email:</label> <input type="email" {...register("email", { required: "Email is required", pattern: { value: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/, message: "Invalid email address", }, })} /> {errors.email && <span>{errors.email.message}</span>} </div> <button type="submit">Submit</button> </form> </div> ); } export default App;

Explanation:

  • useForm: This hook is used to initialize the form. It provides methods like register, handleSubmit, and formState.
  • register: It connects your form inputs with React Hook Form. It takes the name of the input and an optional configuration object (e.g., validation rules).
  • handleSubmit: This function wraps your form submission handler. It ensures that the form is valid before calling the onSubmit function.
  • errors: This is part of formState. It contains any validation errors for the form fields.

Validation Rules:

  • required: Ensures that the field is filled.
  • pattern: Ensures the field matches a specific regex pattern (e.g., email).

Form Submission Output

When you submit the form, the output will be logged in the browser’s console.


3. Controlled vs Uncontrolled Inputs

By default, React Hook Form uses uncontrolled components, which means React doesn't directly manage the form values. However, you can opt for controlled components if necessary.

Here is an example of a controlled component in React Hook Form:


import React, { useState } from "react"; import { useForm } from "react-hook-form"; function App() { const { register, handleSubmit, setValue, getValues, formState: { errors } } = useForm(); const [formValues, setFormValues] = useState({ name: "", email: "" }); const onSubmit = (data) => { console.log("Form Data:", data); }; // Handling controlled inputs with state const handleInputChange = (e) => { setFormValues({ ...formValues, [e.target.name]: e.target.value }); setValue(e.target.name, e.target.value); // Update the value in the react-hook-form state }; return ( <div className="App"> <h1>Controlled Component Example</h1> <form onSubmit={handleSubmit(onSubmit)}> <div> <label>Name:</label> <input type="text" name="name" value={formValues.name} onChange={handleInputChange} {...register("name", { required: "Name is required" })} /> {errors.name && <span>{errors.name.message}</span>} </div> <div> <label>Email:</label> <input type="email" name="email" value={formValues.email} onChange={handleInputChange} {...register("email", { required: "Email is required", pattern: { value: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/, message: "Invalid email address", }, })} /> {errors.email && <span>{errors.email.message}</span>} </div> <button type="submit">Submit</button> </form> </div> ); } export default App;
  • In this example, we use setValue to update the value in the React Hook Form's internal state whenever the input value changes.

4. Form Validation

React Hook Form provides built-in validation capabilities like required, minLength, maxLength, pattern, etc., but you can also use Yup or Joi for more complex validation.

Example with Yup for Validation

First, install Yup and react-hook-form's resolver for Yup:


npm install yup @hookform/resolvers

App.js with Yup Validation:


import React from "react"; import { useForm } from "react-hook-form"; import { yupResolver } from "@hookform/resolvers/yup"; import * as yup from "yup"; const schema = yup.object({ name: yup.string().required("Name is required").min(3, "Name must be at least 3 characters"), email: yup.string().email("Invalid email format").required("Email is required"), }).required(); function App() { const { register, handleSubmit, formState: { errors } } = useForm({ resolver: yupResolver(schema) }); const onSubmit = (data) => { console.log("Form Submitted Data:", data); }; return ( <div className="App"> <h1>React Hook Form with Yup Validation</h1> <form onSubmit={handleSubmit(onSubmit)}> <div> <label>Name:</label> <input type="text" {...register("name")} /> {errors.name && <span>{errors.name.message}</span>} </div> <div> <label>Email:</label> <input type="email" {...register("email")} /> {errors.email && <span>{errors.email.message}</span>} </div> <button type="submit">Submit</button> </form> </div> ); } export default App;

Explanation:

  • yupResolver: This is used to integrate Yup validation with React Hook Form.
  • yup.object(): This creates a validation schema with field validation rules.
  • required, min, email: These are some common validation rules provided by Yup.

Error Handling with Yup:

If there are validation errors, they are displayed under each form field.


5. Dynamic Forms

React Hook Form also supports dynamic forms where you can add or remove form fields dynamically.

App.js with Dynamic Fields Example:


import React, { useState } from "react"; import { useForm, useFieldArray } from "react-hook-form"; function App() { const { control, register, handleSubmit } = useForm(); const { fields, append, remove } = useFieldArray({ control, name: "users", // This will be the field array name }); const onSubmit = (data) => { console.log("Submitted Data: ", data); }; return ( <div className="App"> <h1>Dynamic Form with React Hook Form</h1> <form onSubmit={handleSubmit(onSubmit)}> {fields.map((item, index) => ( <div key={item.id}> <input {...register(`users[${index}].name`, { required: "Name is required" })} defaultValue={item.name} // input default value /> <button type="button" onClick={() => remove(index)}>Remove</button> <br /> </div> ))} <button type="button" onClick={() => append({ name: "" })}>Add User</button> <br /> <button type="submit">Submit</button> </form> </div> ); } export default App;

Explanation:

  • useFieldArray: This hook is used to handle dynamic arrays of fields. You can append new fields or remove existing ones.
  • append(): Adds a new field to the array.
  • remove(): Removes a field from the array based on the index.

Conclusion

In this tutorial, we’ve learned how to use React Hook Form to manage forms in React. We've explored basic usage, form validation with Yup, handling controlled and uncontrolled components, and creating dynamic forms with useFieldArray.

React Hook Form is highly efficient for managing complex forms and integrates well with validation libraries like Yup, making it a powerful tool for building forms in React.

You can visit the official React Hook Form documentation for more advanced use cases and API details.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics