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! 🚀

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️