Initially we create an empty object state for the form. We initialize our form array with. And we initialize the form state as shown below.
const person = {name:'', email:''};
const [form, setForm] = useState([{...person}]);
Second step is to map the form.
<form>
{form.map((person, index) => {
return (
<div key={index}>
<input
name='name'
placeholder='Name'
value={person.name}
onChange={(e)=> handleChange(e, index)}
/>
<input
name='email'
placeholder='Email'
value={person.email}
onChange={(e)=> handleChange(e, index)}
/>
<button onClick={addPerson}> Add person</button>
</div>
)
})}
</form>
export default App;
Step 3 is to write a handle change which uses the index get the position of the person object being updated function to update our form state.
const handleChange = (e, index) =>{
const {name, value} = e.target
const updatedForm = [...form];
updatedForm[index][name] = value;
setForm([...updatedForm]);
}
Now, we will see only one set of input fields, because we have only one object in the form state. If we add more objects, we will see multiple input fields.
In order to create more persons we would create a function to add a new object to the array.
Lastly we add a removePerson function in any case where a user needs to delete a person.
const addPerson = () => {
setForm([...form, {...person}])
}
const removePerson = (position) => {
setForm(form.filter((i, index)=> index !== position))
}
Here is how the entire code goes
import { useState } from 'react'
import './App.css'
function App() {
const person = {name:'', email:''};
const [form, setForm] = useState([{ ...person }]);
const handleChange = (e, index) =>{
const {name, value} = e.target
const updatedForm = [...form];
updatedForm[index][name] = value;
setForm([...updatedForm]);
}
const addPerson = () => {
setForm([...form, {...person}])
}
const removePerson = (position) => {
setForm(form.filter((i, index)=> index !== position))
}
return (<div>
<form>
{form.map((person, index) => {
return (
<div key={index}>
<input
name='name'
placeholder='Name'
value={person.name}
onChange={(e)=> handleChange(e, index)}
/>
<input
name='email'
placeholder='Email'
value={person.email}
onChange={(e)=> handleChange(e, index)}
/>
<p onClick={()=>removePerson(index)}>Remove person</p>
</div>
)
})}
</form>
<button onClick={addPerson} className=''>Add person</button>
</div>
)
}
export default App
That will be all for this article,
Leave a like and comment.
Happy, coding!
Top comments (3)
Better to use a reducer if you want to update a property in a state object.
Your reducer function would be something like:
And you can just call your dispatch like this:
Btw, I wouldn't make one big form as it violates single responsibility, rather make a form per person and the persons array can be state that lives in the App component.
I am using React version 18.
Thanks for this. What version of react are you using?