I am using React, my state is defined as an array of object. I need to be able to change only one specific element in the state.data array, example object with id 1.
I would like to know:
setState()
in this scenario.constructor(props) {
super(props);
this.state = {
data: [{
id: 0,
title: 'Buy a',
status: 0, // 0 = todo, 1 = done
},
{
id: 1,
title: 'Buy b',
status: 0,
},
{
id: 2,
title: 'Buy c',
status: 0,
}
]
};
this.onTitleChange = this.onTitleChange.bind(this);
}
onTitleChange(id, title) {
console.log(id, title);
debugger
}
To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!
To implement the change of item on click, we will create the list data as a state in react by using the useState hook. Then on onClick we will change the item. Step 3: Create folder components inside src folder of react project directory and inside the components folder create files List. jsx.
You can get do a cloning of the state object using spread operator and then find the index of object in array with a given id using findIndex
method Modify the object and set the state.
constructor(props) {
super(props);
this.state = {
data: [{
id: 0,
title: 'Buy a',
status: 0, // 0 = todo, 1 = done
},
{
id: 1,
title: 'Buy b',
status: 0,
},
{
id: 2,
title: 'Buy c',
status: 0,
}
]
};
this.onTitleChange = this.onTitleChange.bind(this);
}
onTitleChange(id, title) {
var data = [...this.state.data];
var index = data.findIndex(obj => obj.id === id);
data[index].title = title;
this.setState({data});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With