DEV Community

Cover image for Using React Hook Forms to make handling forms easier
Momin Mahmud
Momin Mahmud

Posted on

Using React Hook Forms to make handling forms easier

Introduction

React Hook Form is a powerful library for handling forms in React using hooks. It simplifies form management by reducing boilerplate code and providing efficient validation. In this extended blog post, we’ll explore how to use React Hook Form’s useFieldArray to create dynamic forms with ease.

Prerequisites

Before we begin, make sure you have the following installed:

Node.js
npm or yarn (for package management)
Enter fullscreen mode Exit fullscreen mode

Setting Up the Project
Create a new React project using create-react-app or any other preferred method.
Install React Hook Form:

npm install react-hook-form
# or
yarn add react-hook-form
Enter fullscreen mode Exit fullscreen mode

Creating a Simple Form

Let’s start with a basic form that collects user information. We’ll create a form with fields for name and email. If any field is empty, we’ll display an error message.

import React from 'react';
import { useForm } from 'react-hook-form';

const SimpleForm = () => {
  const { register, handleSubmit, errors } = useForm();

  const onSubmit = (data) => {
    console.log(data); // Handle form submission
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        type="text"
        name="name"
        placeholder="Name"
        ref={register({ required: true })}
      />
      {errors.name && <p>Name is required</p>}

      <input
        type="email"
        name="email"
        placeholder="Email"
        ref={register({ required: true, pattern: /^\S+@\S+$/i })}
      />
      {errors.email && <p>Valid email is required</p>}

      <button type="submit">Submit</button>
    </form>
  );
};

export default SimpleForm;

Enter fullscreen mode Exit fullscreen mode

Adding Dynamic Fields with useFieldArray

Now, let’s enhance our form by allowing users to add multiple ticket details. We’ll use useFieldArray to manage an array of ticket fields dynamically.

import React from 'react';
import { useForm, useFieldArray } from 'react-hook-form';

const DynamicForm = () => {
  const { register, handleSubmit, control } = useForm();
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'tickets',
  });

  const onSubmit = (data) => {
    console.log(data); // Handle form submission
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {fields.map((field, index) => (
        <div key={field.id}>
          <input
            type="text"
            name={`tickets[${index}].name`}
            placeholder="Ticket Name"
            ref={register()}
          />
          <input
            type="email"
            name={`tickets[${index}].email`}
            placeholder="Ticket Email"
            ref={register()}
          />
          <button type="button" onClick={() => remove(index)}>
            Remove
          </button>
        </div>
      ))}
      <button type="button" onClick={() => append({ name: '', email: '' })}>
        Add Ticket
      </button>
      <button type="submit">Submit</button>
    </form>
  );
};

export default DynamicForm;

Enter fullscreen mode Exit fullscreen mode

Conclusion

In this extended blog post, we covered how to create a simple form using React Hook Form and then extended it to handle dynamic fields with useFieldArray. Feel free to explore more features of React Hook Form to enhance your form-building experience!

Remember to check out the complete example on GitHub and experiment with it yourself. Happy coding! 🚀

Top comments (0)