DEV Community

Nikhil Soni
Nikhil Soni

Posted on Edited on

Handling multiple inputs in react.

Hello everyone,
In this article, let us understand how to handle multiple inputs in react.

Recently I was working on one side project where I had multiple input fields.

Let's take the example of the below code.

const Form = () => {
  const [name, setName] = useState('');
  const [age, setAge] = useState('');
  const [country, setCountry] = useState('');
  console.log(name, age, country);
  return (
    <form>
      <input
        type='text'
        value={name}
        onChange={(e) => {
          setName(e.target.value);
        }}
      />
      <input
        type='text'
        value={age}
        onChange={(e) => {
          setAge(e.target.value);
        }}
      />
      <input
        type='text'
        value={country}
        onChange={(e) => {
          setCountry(e.target.value);
        }}
      />
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

In the above example we have 3 different input fields, we may have more than 3 also, and 3 different states and 3 onChange function to update respective states.

We can solve this problem with help of the following approach.

const AnotherForm = () => {
  const [inputValues, setInputValues] = useState({
    name: '',
    age: '',
    country: '',
  });
  const inputChangeHandler = (e) => {
    const { id, value } = e.target;
    setInputValues({ ...inputValues, [id]: value });
  };
  
  return (
    <form>
      <input
        id='name'
        type='text'
        value={inputValues.name}
        onChange={inputChangeHandler}
      />
      <input
        id='age'
        type='text'
        value={inputValues.age}
        onChange={inputChangeHandler}
      />
      <input
        id='country'
        type='text'
        value={inputValues.country}
        onChange={inputChangeHandler}
      />
    </form>
  );
};

Enter fullscreen mode Exit fullscreen mode

In this solution, we have to manage only one state which is having a object, with property of the respective input field, as an initial value. All input fields will have value attribute with their respective value. e.g value={inputValues.name}.
We will define one single handler function inputChangeHandler, which will handle onChange event for every input change.

How does all this work? let us understand step by step.

  • First we are destructuring e.target object to get  id and value attributes from input fields.
  • Then we are updating inputValues state object with existing values with help of setInputValues and spread operator.
  • And now we are updating value of the input field that is being triggered with onChange. e.g. - [id] : value, here we are setting dynamic id property key.

Top comments (0)