Add/Remove input fields dynamically in React

share link

by Abdul Rawoof A R dot icon Updated: Feb 10, 2023

technology logo
technology logo

Solution Kit Solution Kit  

To make the form with input fields dynamically, we'll create a React state, and this state will have an object. Create an input group and add an input field along with a button i.e the button which is used to delete this input field. Then create a button and on clicking this button we'll dynamically add the input fields.

The main function which is used to add the input fields and remove the input fields is the click() function. It plays a vital role for add and remove the input fields. If we click an "Add" button then a new input field will be added in the DOM. If we want to add one or more input fields then just click again and again the "Add" button to add input fields dynamically. We can add as many as possible input fields according to our needs by just clicking the "Add" button. Also, we can remove those input fields which are added by just clicking the "Remove" button. To add multiple input fields dynamically in React, first, create an array in the state variable then assign a name to the dynamic fields with the help of array indexing like name0, name1.

Steps to Add and Remove Form fields dynamically with React,

  1. Create a form field with input like name and email.
  2. Create add and remove fields by adding functions.
  3. Functional component with complete example.
  4. Class component with complete example.
  5. Then, CSS code.

Here is an example of how you can Add and Remove input fields dynamically in React: