Search code examples
javascriptreactjsstatesetstate

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

Solution

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

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