How to identify different inputs with one onChange handler with React?

Sometimes, we want to identify different inputs with one onChange handler with React.

In this article, we’ll look at how to identify different inputs with one onChange handler with React.

How to identify different inputs with one onChange handler with React?

To identify different inputs with one onChange handler with React, we can create a function that gets the name attribute value of the field and put it in the state object as a property with the value of the same input as the value.

For instance, we write

import React, { useState } from "react";

export default function Exapmle() {
  const [userState, setUserState] = useState({
    firstName: "",
    lastName: "",
  });

  const handleChange = (e) => {
    const value = e.target.value;
    setUserState({
      ...userState,
      [e.target.name]: value,
    });
  };

  return (
    <form>
      <label>
        First name
        <input
          type="text"
          name="firstName"
          value={userState.firstName}
          onChange={handleChange}
        />
      </label>

      <label>
        Last name
        <input
          type="text"
          name="lastName"
          value={userState.lastName}
          onChange={handleChange}
        />
      </label>
    </form>
  );
}

to add 2 inputs with different name attribute values.

Then we define the handleChange function that gets the input value with e.target.value.

And we call setusetState with an object that has the existing userState properties.

And we add the [e.target.name] property with its value set to value.

e.target.name returns the name attribute value of the input.

Conclusion

To identify different inputs with one onChange handler with React, we can create a function that gets the name attribute value of the field and put it in the state object as a property with the value of the same input as the value.