DEV Community

Cover image for Best way to build a dynamic input form with react.
Abdulsamad Ajao
Abdulsamad Ajao

Posted on

Best way to build a dynamic input form with react.

Image description

Image description

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}]);
Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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]);
}
Enter fullscreen mode Exit fullscreen mode

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))
  }
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

That will be all for this article,
Leave a like and comment.
Happy, coding!

Top comments (3)

Collapse
 
brense profile image
Rense Bakker

Better to use a reducer if you want to update a property in a state object.

Your reducer function would be something like:

function formReducer(currentState, nextState){
  return { ...currentState, ...nextState }
}
Enter fullscreen mode Exit fullscreen mode

And you can just call your dispatch like this:

dispatch({ [e.target.name]: e.target.value })
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
ajaoseyi profile image
Abdulsamad Ajao

I am using React version 18.

Collapse
 
sammybammy52 profile image
Seye Yemi-Olowolabi

Thanks for this. What version of react are you using?