Categories
React Answers

How to Edit Multiple Controlled Input Components’ Values in React?

Spread the love

Sometimes, we want to edit the value of multiple controlled input components in React.

In this article, we’ll look at how to edit the value of multiple controlled input components in React.

Edit Multiple Controlled Input Components’ Values in React

To edit the value of multiple controlled input components in React, we can create a function that returns the onChange callback for each input.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [contact, setContact] = useState({ firstName: "", lastName: "" });

  const handleChange = (propertyName) => (event) =>
    setContact((c) => ({ ...c, [propertyName]: event.target.value }));

  return (
    <div>
      <input
        type="text"
        onChange={handleChange("firstName")}
        value={contact.firstName}
      />
      <input
        type="text"
        onChange={handleChange("lastName")}
        value={contact.lastName}
      />
    </div>
  );
}

We have the contact state which is set to an object with the firstName and lastName properties as its initial value.

Then we create the handleChange function that takes propertyName and calls setContact to update the contact state’s propertyName property with the inputted value, which is stored in e.target.value .

Then we have 2 inputs with the value props set to each contact property.

And the onChange props are set to functions returned by handleChange with the propertyName to set the contact ‘s firstName or lastName property depending on the field.

Conclusion

To edit the value of multiple controlled input components in React, we can create a function that returns the onChange callback for each input.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *