9

Is there a way to use a string variable's value as the key for setState()?

getInitialState: function () {
    return {
        foo: '',
        bar: ''
    }
}

someOtherHandler: function() {
    var arr = ['foo', 'bar'];
    var _this = this;
    var number = Math.random();

    for (var i in arr) {
        _this.setState({ arr[i]: number });
    }

}

React throws a syntax error with the above, and setting arr[i] to a variable ends up setting a new state with that variable's name.

cy23
  • 1,221
  • 1
  • 10
  • 7

1 Answers1

22

You can create the object before calling setState.

var newState = {};
newState[i] = number;
_this.setState(newState);

Alternatively if you are using ES6, you could make use of a computed property.

_this.setState({ [i]: number });

However this code will call setState multiple times, it's more efficient to only call it once. Build the updated state object, then apply it.

var newState = {};

for(var i in arr) {
  newState[i] = number;
}

this.setState(newState);
Dan Prince
  • 29,491
  • 13
  • 89
  • 120
  • Thanks a lot! I had actually just run across a similar question that essentially pointed me to the same thing: http://stackoverflow.com/questions/29280445/reactjs-setstate-with-a-dynamic-key-name – cy23 Dec 10 '15 at 05:35