Achilles Achilles - 1 year ago 142
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++) {
innerArray.push("empty");
}
board.push(innerArray);
}
return {board: board};
},


The line below doesn't seem to work:

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


Edit: Why do I get downvoted?!

Answer Source

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})

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download