Calvin-Castle
Calvin-Castle

Reputation: 111

Setting a React JS State via a Parameter

I am wondering if it is possible to create a function that takes in a parameter (either a string of the state name or the actual state) then set the state of the state relating to the parameter.

SetState(x) {
        // Assume x can be any state we have already declared (I need it work for multiple states)
        this.setState((x): false);
    }

Upvotes: 0

Views: 38

Answers (1)

Andy
Andy

Reputation: 63524

Yes. You put the param in square brackets to create a dynamic key:

doSetState(str) {
  this.setState({ [str]: false });
}

Upvotes: 2

Related Questions