Add or Remove input fields dynamically with React Hooks
In this article we will see how to add or remove form input fields dynamically in react js with hooks. In a project many times you need to add details dynamically i.e add your family members name, add your favourite subject etc.
Steps to create dynamic input fields:
- Create react project
- Design form with input (here first name and last name in input)
- Add functions to add and remove fields and handle change of input
Step-1 Create react project:
Create a react project by using creat-react-app command. I have used material-ui for design. Go and checkout installation steps, you can use any design or normal html css.
Step-2 Design form with input:
In above code you can see useState() with formInputs variable with default value and in design by using map we are displaying input.
Step-3 Add functions to add and remove fields and handle change of input:
OnChange: using name and index in this function we are handling onchange on input to set the value of it.
onAddClick: this method is used to add a new field in the input list.
onRemoveClick: Using index we are removing the input field from the list.
Full code:
Add all code in one file and run it. you can see code on github https://github.com/AvaniBataviya/dynamic-input-field
Out Put:
Check live out put: https://stackblitz.com/edit/react-w3wrhq
Checkout my previous blog, how to make reusable form input component in reactjs and all form common components on my git hub. https://github.com/AvaniBataviya/react-common-component
Thank you!