React Update State onChange in an Array of Objects using React Hooks

In our daily programming we widely use array and array of objects. We need to update array and array of objects in most of our works. We might know how to update an array in onChange but never wondered how to update the states in an array of objects.

In this article, we'll learn how to update states of an array of objects in react hooks after onChange event.

We will create an array and store it inside the useState hook. Then, we will make a function updateState that will handle our onChange property.

Let's see it in action:

Table of Contents

  1. Creating an array with useState()
  2. Function declaration to update state on change occur
  3. Final Output

Creating an array with useState()

In your react app create an array with some sample data. Store the array in the useState hook. Here is an example:

 const array = [
    {
      id: 1,
      name: 'Jon'
    },
    {
      id: 2,
      name: 'Doe'
    }
  ];

 const [data, setData] = useState(array);

Function declaration to update state on change occur

Now, we will declare a function updateState() that contains a callback function which checks the index.

This function then maps into the data and returns a new array of objects containing all the properties. 

  const updateState = (index) => (e) => {
    const temp = datas.map((item, idx) => {
      if (index === idx) {
        return { ...item, [e.target.name]: e.target.value };
      } else {
        return item;
      }
    });
    setData(temp);
  };

It spread the contents of the array we declare of out first step in a new object that we declare temp, then replace the object in the selected index, and finally creates an array from that result. And finally we update  our state with setData to the array returned.

Final Output

And the final output of our code will be:

import React, { useState } from 'react';


const array = [
    {
      id: 1,
      name: 'Jon'
    },
    {
      id: 2,
      name: 'Doe'
    }
  ];
  
const App = () => {

  const [datas, setDatas] = useState(array);

  const updateState = (index) => (e) => {
    const temp = datas.map((item, i) => {
      if (index === i) {
        return { ...item, [e.target.name]: e.target.value };
      } else {
        return item;
      }
    });
    setDatas(temp);
  };

  return (
    <div className="App">
      <p>Updating array of objects!</p>
      {datas.map((data, index) => {
        <li key={data.id}>
          <input
            type="text"
            name="name"
            value={data.name}
            onChange={updateState(index)}
          />
        </li>;
        })}
    </div>
  );
}

export default App;

That's it for today. I hope you've enjoyed this tutorial. Thanks for reading. ๐Ÿ™‚