Achilles Achilles - 8 months ago 17
Javascript Question

How can I change an array in a state in React?

I'm using a 2-dimensional array as a state.

How can I update it?

getInitialState: function() {
var board = [];
for (var i = 0; i < i_max; i++) {
var innerArray = [];
for (var j = 0; j < j_max; j++) {
return {board: board};

The line below doesn't seem to work:

this.setState({board[1][2]: "full"});

Edit: Why do I get downvoted?!


State is kept as a map, so the way that you're editing doesn't really make sense. My recommendation is to treat the previous state as "immutable" (my example isn't actually doing that) and replace the value wholesale.

var changedBoards = this.state.boards changedBoards[0][1] = "full"; this.setState({boards: changedBoards})