How can I insert into React's state array with setState? How can I insert into React's state array with setState? reactjs reactjs

How can I insert into React's state array with setState?


enter image description here

Clone the current state using slice(). By doing this, the original state remains unaffected till setState(). After cloning, do your operations over the cloned array and set it in the state. The previous answer will mutate the state. Read about this here

let a = this.state.arr.slice(); //creates the clone of the statea[index] = "random element";this.setState({arr: a});


use spread operator https://codeburst.io/javascript-es6-the-spread-syntax-f5c35525f754

let newChild = "newChild"this.setState({    children: [        ...this.state.children,        newChild    ]})


UPDATE

Just use Object.assign() as suggested here to make a copy of your state.

Thus, you can do it as follows :

let new_state = Object.assign({}, this.state); let a = new_state.arr;a[index] = "random element";this.setState({arr: a});

Hope it helps.