0

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);
    }
2
  • Can you add a few examples of how you'd call this function? It sounds like setState already does what you want... Commented Jul 14, 2019 at 12:12
  • yes you can do that with parameter. Commented Jul 14, 2019 at 12:14

1 Answer 1

2

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

doSetState(str) {
  this.setState({ [str]: false });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.