Categories
React Answers

How to edit multiple input controlled components in React?

Spread the love

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

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

How to edit multiple input controlled components in React?

To edit multiple input controlled components in React, we can create a function that returns the change event handler function according to the property we want to edit.

For instance, we write:

import React, { useState } from "react";

const initialContact = { firstName: "", lastName: "", phone: "" };

export default function App() {
  const [contact, setContact] = useState(initialContact);

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

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

We define the contact state with the useState hook.

Then we have the handleChangeFor function that takes the propertyName to change.

And we return the change event handler function that calls setContact to change the contact state to update the propertyName property’s value by setting it to e.target.value.

e.target.value has the inputted value.

Finally, we set the onChange prop of each input to the event handlers returned by handleChangeFor called with the property name of each contact property.

Conclusion

To edit multiple input controlled components in React, we can create a function that returns the change event handler function according to the property we want to edit.

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 *