Chrome Extension

[React]Add or push values to array defined in state

var newArr = this.state.arr.concat('new value');
this.setState({ myArray: newArr });

//USING es6 IT CAN BE DONE PRETTY EASILY

//PUSH ITEM TO THE END OF AN ARRAY
this.setState({
    arr: [...this.state.arr, "new value"]
});

//ADD NEW ARRAY AS A LAST ELEMENT
this.setState({
    arr: [...this.state.arr, ["a", "b", "c"]]
});

//PUSH OBJECT OR ITEM TO THE START OF ARRAY
this.setState({
    arr: [{"name": "value"}, ...this.state.arr]
});

You can use dot operators to insert new values to the array if you are using ES6 or you can also concatenate an array to the new values using .concat() function. 

Was this helpful?
0 Comments
Never leave your website again in search of code snippets by installing our chrome extension.