Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm looking to modify and array in react and insert elements on specific index. This is how my state looks like:

this.state = {arr: ['', '', '', '' ]}

What I wanna do is to compile this arr[index] = 'random element' to react js setState syntax. What I tried to do was:

this.setState({ arr[index]: 'random element' })

but failed, ty!

like image 387
alex1997 Avatar asked Sep 07 '25 11:09

alex1997


2 Answers

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 state
a[index] = "random element";
this.setState({arr: a});
like image 76
Pranesh Ravi Avatar answered Sep 09 '25 01:09

Pranesh Ravi


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

let newChild = "newChild"

this.setState({
    children: [
        ...this.state.children,
        newChild
    ]
})
like image 44
Aldo Makmur Avatar answered Sep 09 '25 01:09

Aldo Makmur