You might know how to update the onChange in an array but have you ever wondered how you can update the states in an array of objects and reflect new changes?
In this article, we’ll look at how to update states onChange in an array of objects using React Hooks.
To update the state in an array of objects when the change occurs (onChange). 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.
Creating an array with useState()
In your React app create a datas array with a couple of objects as in the code below. Store the datas array in the useState hook.
// App.js
const datas = [
{
id: 1,
name: 'Nick',
age: 21
},
{
id: 2,
name: 'Lara',
age: 30
}
];
const [data, setData] = useState(datas);
Function to update state when the change occurs.
The updateState() contains a callback function that checks the index.
The function then maps into the data and returns a new array of objects containing all the properties.
It spread the contents of the datas array in a new object, then replace the object in the selected index, and finally creates an array from that result,
Then, we update our state setData to the array returned.
// App.js
const updateState = (index) => (e) => {
const newArray = data.map((item, i) => {
if (index === i) {
return { ...item, [e.target.name]: e.target.value };
} else {
return item;
}
});
setData(newArray);
};
Create an input field as in the code below that will be updated every time user makes changes in the input field with the help of our updateState function.
Set the onChange prop to the updateState function and pass the index as a parameter.
// App.js
import { useState } from 'react';
import './App.css';
function App() {
const datas = [
{
id: 1,
name: 'Nick',
age: 21
},
{
id: 2,
name: 'Lara',
age: 30
}
];
const [data, setData] = useState(datas);
const updateState = (index) => (e) => {
const newArray = data.map((item, i) => {
if (index === i) {
return { ...item, [e.target.name]: e.target.value };
} else {
return item;
}
});
setData(newArray);
};
return (
<div className="App">
<p>Hello, world!</p>
{data.map((datum, index) => {
<li key={datum.name}>
<input
type="text"
name="name"
value={datum.name}
onChange={updateState(index)}
/>
</li>;
})}
</div>
);
}
export default App;
Conclusion
Hopefully, by now you understand how to update the state in an array of objects. You must have known how to update the state in arrays but in this article, we updated the state of an array of objects.
Feel free to comment if you have any questions or If you have suggestions. If you want to request any article for a particular topic, contact us through the about page. We would love to hear from you.
💬 Leave a comment