Hey everyone, I am trying to create a generic toggle function in my React application using Semantic UI React. I have a properties on my application’s state which are object arrays. The object arrays looks like this:
this.state = {
days: [
{
name: 'M',
value: true
},
{
name: 'Tu',
value: true
},
{
name: 'W',
value: true
},
{
name: 'Th',
value: true
},
{
name: 'F',
value: true
},
{
name: 'Sa',
value: true
},
{
name: 'Su',
value: true
}
]
}
Since there are multiple object arrays like this, I am trying to make my handleToggle function generic to handle toggling any object array. So the handle toggle function takes in the group(object array name) and index from the click event. I then want to change the value on the object and then update the state. I am having issues figuring out the syntax on the return statement in the setState function. Here is my function:
handleToggle = (e, data) => {
let {idx, group} = data;
this.setState((previousState)=>{
let toggledItem = previousState[group][idx]; //this targets the object which is being toggled
return {
...previousState, [toggledItem]: !previousState[group][idx].value //not sure of the syntax here...
}
});
}
I have seen plenty of demonstrations which look like the one below, but they don’t help me in figuring out how to change just the property on object within the state. Any help would be much appreciated. Thank you!
function incrementFooBy(delta) {
return (previousState, currentProps) => {
return { ...previousState, foo: previousState.foo + delta };
};
}