Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update an array at a particular index with React js

Tags:

reactjs

I have a state array in my constructor:

constructor(props) {
   super(props);
   this.state = {myarray: []};
}

Now I want to update the array at a specific subscript.

this.setState({myarray[i]: 'test'});

gives me an unexpected token error, pointing at the opening bracket [

What is the correct way of doing that?

P.S. Array gets filled dynamically using push method and only then I attempt to update

like image 803
Coding Duchess Avatar asked Feb 05 '23 03:02

Coding Duchess


1 Answers

Create a copy of the array:

const newArray = Array.from(this.state.myarray);

update the index:

newArray[i] = 'test';

and update the state

this.setState({myarray: newArray});

You can also use immutable helpers (used to be part of React's addons) to do this more concisely.

like image 94
Felix Kling Avatar answered Feb 08 '23 02:02

Felix Kling