How to Handle Multiple Inputs with React Hooks

Here I am going to explain one of the best and common practices of handling multiple inputs with React Hooks. It’s possible to handle all inputs of a form by using a single state and onChange function. Let’s see in action.

First of all, we can initialize a state as an object with all input fields.

  const [inputs, setInputs] = useState({
    name: "",
    email: ""
  })

Then, create a form with all our controlled inputs. Since we only have a single onChange function, the given name must match with our inputs state

 <form>
      <input type="text" name="name" value={inputs.name} onChange={changeHandle}/>
      <input type="email" name="email" value={inputs.email} onChange={changeHandle}/>
 </form>

Now, we can add our changeHandle function to update the properties of our inputs state.

  const changeHandle = e => {
    setInputs({
      ...inputs,
      [e.target.name]: e.target.value
    })
  }

Here, we use the Javascript spread operator to update the value of our current state with user input values.

Final Code

import React, { useState } from 'react';

const App = () => {

  const [inputs, setInputs] = useState({
    name: "",
    email: ""
  })

  const changeHandle = e => {
    setInputs({
      ...inputs,
      [e.target.name]: e.target.value
    })
  }

  const submitHandle = e => {
    e.preventDefault()
    console.log(inputs)
  }
  
  return (
    <form onSubmit={submitHandle}>
      <input type="text" name="name" value={inputs.name} onChange={changeHandle} />
      <input type="email" name="email" value={inputs.email} onChange={changeHandle} />
      <button type="submit">Submit</button>
    </form>
  );
}

export default App;

I hope you understand this way of handling multiple inputs with React hooks. You will see more advantages of this method when creating reusable components.

Similar Posts

Leave a Reply