Add and Remove Form fields dynamically with React and React Hooks
In this article, we will learn how we can add and remove form input fields dynamically. We will use react functional components to illustrate but At the end of this post complete code is shared to implement this logic using both types of React components class components and functional components.
Step 1: Create a form with inputs name and email.
In the above code, you can see React useState hook with array to set default values. The map() method is used to iterate state elements.
Step 2: Add functions to create add and remove fields
- handleChange: This function is used to set input field values based on an index and name on Change.
- addFormFields : Method is used to add a new element with input fields.
- removeFormFields : To remove elements based on an index.
Complete Example with Function component
Complete Example with Class component