Remove Functionality in Dynamic Form using React Hook Form

Remove Functionality in Dynamic Form using React Hook Form

In this blog post, we will explore how to implement the "Remove" functionality in a dynamic form using React Hook Form. Dynamic forms allow users to add and remove fields as needed, making it a versatile solution for various data entry scenarios.

For this tutorial, we'll use an example React component App that utilizes React Hook Form to manage form fields dynamically. We will focus on adding Remove functionality to the address fields within the form.

Here is the initial code for the App component:

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

const App = () => {
  const { register, handleSubmit, control } = useForm({
    defaultValues: {
      firstName: "",
      lastName: "",
      email: "",
      addresses: [
        {
          street: "",
          city: "",
          zip: ""
        }
      ]
    }
  });

  const { fields, append, remove } = useFieldArray({
    control,
    name: "addresses"
  });

  const onSubmit = (data) => {
    console.log(data);
  };

  // ...rest of the component
};

Adding the "Remove" Functionality

To implement the "Remove" functionality, we need to:

  1. Create a button for each address field that allows the user to remove it.

  2. Handle the removal of the corresponding address field when the button is clicked.

Here's the code to add the "Remove" functionality:

{fields.map((field, index) => (
  <div
    className="mb-6 p-6 flex flex-col bg-gray-50 rounded-md shadow-md"
    key={field.id}
  >
    <button
      onClick={() => remove(index)} // Remove the address field at the current index
      className="bg-red-600 font-semibold px-6 py-2 mb-4 rounded-md text-white hover:bg-red-700 transition duration-300 self-end"
    >
      Remove
    </button>

    <!-- Rest of the address fields -->
  </div>
))}

In this code, we use the fields.map function to iterate over the dynamic address fields and render a "Remove" button for each. The onClick handler for the "Remove" button calls the remove function from useFieldArray, passing the current index as an argument. This effectively removes the address field associated with that index.

Complete App Component

Here's the complete App component with the "Remove" functionality:

Here's the code to add the "Remove" functionality:

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

const App = () => {
  const { register, handleSubmit, control } = useForm({
    defaultValues: {
      firstName: "",
      lastName: "",
      email: "",
      addresses: [
        {
          street: "",
          city: "",
          zip: ""
        }
      ]
    }
  });

  const { fields, append, remove } = useFieldArray({
    control,
    name: "addresses"
  });

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <div className="flex items-center justify-center min-h-screen bg-gray-100">
      <form
        className="w-[600px] p-8 bg-white rounded-lg shadow-lg"
        onSubmit={handleSubmit(onSubmit)}
      >
        <h1 className="text-3xl text-center font-semibold text-gray-900 mb-6">
          Address Form
        </h1>
        <div className="mb-6 p-6 bg-gray-50 rounded-md shadow-md">
          <!-- First Name, Last Name, and Email fields -->
        </div>
        {fields.map((field, index) => (
          <div
            className="mb-6 p-6 flex flex-col bg-gray-50 rounded-md shadow-md"
            key={field.id}
          >
            <button
              onClick={() => remove(index)}
              className="bg-red-600 font-semibold px-6 py-2 mb-4 rounded-md text-white hover-bg-red-700 transition duration-300 self-end"
            >
              Remove
            </button>
            <!-- Address fields -->
          </div>
        ))}
        <div className="flex items-center justify-end mt-6">
          <button
            className="bg-blue-500 font-semibold px-6 py-2 rounded-md text-white hover:bg-blue-600 transition duration-300"
            onClick={() => append({ street: "", city: "", zip: "" })}
            type="button"
          >
            Add Address
          </button>
          <button
            className="bg-blue-500 font-semibold ml-4 px-6 py-2 rounded-md text-white hover-bg-blue-600 transition duration-300"
            type="submit"
          >
            Submit
          </button>
        </div>
      </form>
    </div>
  );
};

export default App;

In this code, we use the fields.map function to iterate over the dynamic address fields and render a "Remove" button for each. The onClick handler for the "Remove" button c

Now, when a user clicks the "Remove" button for a specific address, that address field will be removed from the form, providing a dynamic and flexible form-building experience for your application.

Key Insights

In this tutorial, we explored how to implement the "Remove" functionality in a dynamic form using React Hook Form. The dynamic form allows users to add and remove address fields as needed, which can be useful in various data entry scenarios.

Here are the key insights from this tutorial:

  1. React Hook Form: We used React Hook Form to manage the form and its dynamic fields. React Hook Form is a powerful library for handling forms in React applications, making form management more efficient and user-friendly.

  2. Dynamic Form Fields: We demonstrated how to create a dynamic form with a list of address fields. Users can add multiple address sections, and each section can be removed independently, providing flexibility and a clean user experience.

  3. "Remove" Functionality: We added a "Remove" button for each address field, allowing users to remove a specific address entry. This is achieved by using the useFieldArray hook's remove function with the appropriate index.

Conclusion

Implementing a dynamic form with the "Remove" functionality in React Hook Form can greatly improve the user experience for data entry forms. Users can add and remove fields as needed, ensuring the form adapts to their requirements.

By following the steps in this tutorial, you can create interactive and user-friendly forms in your React applications. React Hook Form simplifies form management and, when combined with dynamic form features, offers a versatile solution for various form-based tasks.

Remember that React Hook Form provides a robust set of tools for form handling, and you can further customize and extend the form's functionality to meet your specific application needs. The "Remove" functionality is just one example of how you can enhance the user experience in your forms.

So go ahead and enhance your forms with dynamic and user-friendly features using React Hook Form!