Categories
React Answers

How to update states onChange in an array of objects in React Hooks?

Spread the love

Sometimes, we want to update states onChange in an array of objects in React Hooks.

In this article, we’ll look at how to update states onChange in an array of objects in React Hooks.

How to update states onChange in an array of objects in React Hooks?

To update states onChange in an array of objects in React Hooks, we can return a new array with the new input value.

For instance, we write

const Comp = () => {
  const [data, setData] = useState([
    {
      id: 1,
      name: "john",
      gender: "m",
    },
    {
      id: 2,
      name: "mary",
      gender: "f",
    },
  ]);

  const updateFieldChanged = (index) => (e) => {
    const newArr = data.map((item, i) => {
      if (index === i) {
        return { ...item, [e.target.name]: e.target.value };
      } else {
        return item;
      }
    });
    setData(newArr);
  };

  return (
    <>
      {data.map((datum, index) => {
        <li key={datum.name}>
          <input
            type="text"
            name="name"
            value={datum.name}
            onChange={updateFieldChanged(index)}
          />
        </li>;
      })}
    </>
  );
};

to define the data state with useState.

Then we define the updateFieldChanged function that calls data.map with a callback that checks if index is i.

If it is, then we return a new object with the existing properties of item.

And we add the [name] property and set it to the e.target.value input value.

Then we call setData with newArr to update the state to the array returned by map.

Finally, we render the li elements with the inputs inside.

And we set the onChange prop to the function returned by updateFieldChanged called with index.

Conclusion

To update states onChange in an array of objects in React Hooks, we can return a new array with the new input value.

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 *