Add/Remove input fields dynamically in React
by Abdul Rawoof A R Updated: Feb 10, 2023
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,
- Create a form field with input like name and email.
- Create add and remove fields by adding functions.
- Functional component with complete example.
- Class component with complete example.
- Then, CSS code.
Here is an example of how you can Add and Remove input fields dynamically in React: