how to setstate elements inside an array in react code example
Example 1: react how to update state array
const initialState = [
{ name: "foo", counter: 0 },
{ name: "far", counter: 0 },
{ name: "faz", counter: 0 }
];
const [state, setState] = useState(initialState);
const clickButton = () => {
let temp_state = [...state];
let temp_element = { ...temp_state[0] };
temp_element.counter = temp_element.counter+1;
temp_state[0] = temp_element;
setState( temp_state );
}
Example 2: setstate react js
constructor(props) {
super(props);
this.state = {
isActive: true,
};
}
checkStatus = () => {
this.setState({
'isActive' : !this.state.isActive,
});
}
Example 3: update object in array state by index
this.setState(({items}) => ({
items: [
...items.slice(0,1),
{
...items[1],
name: 'newName',
},
...items.slice(2)
]
}));
Example 4: react setState
this.setState({
date: new Date()
});