0

I am new to React and try to load different components based on state variables. I want my handler to dynamically know which state variable I am updating. As of now, I am explicitly passing the state name as a string.

State Variables

state = {
        showLogin: false,
        showHome: false
    }

Handler Method

handleShow = (element) => this.setState({ element: true });

Buttons

{
  !this.props.isAuthenticated ? (
    <Button
      variant="outline-primary"
      onClick={() => this.handleShow("showLogin")}
    >
      Login
    </Button>
  ) : (
    <>
      <Button
        variant="outline-primary"
        onClick={() => this.handleShow("showHome")}
      >
        Home
      </Button>
      <Button variant="outline-primary" onClick={this.authorizeUserMethod}>
        LogOut
      </Button>
    </>
  );
}
keikai
  • 14,085
  • 9
  • 49
  • 68
Avi
  • 102
  • 1
  • 9
  • Does this answer your question? [How do I create a dynamic key to be added to a JavaScript object variable](https://stackoverflow.com/questions/2462800/how-do-i-create-a-dynamic-key-to-be-added-to-a-javascript-object-variable) – ksav Mar 23 '20 at 04:02
  • No @Ksav. My question is more related to 'element' here. I am passing state variable as string eg: "showLogin", "showHome" but it not working. How can I pass the name of the state variable dynamically? – Avi Mar 24 '20 at 01:53
  • `element` is a variable. The linked question deals with how to use the variable as a dynamic object key. – ksav Mar 24 '20 at 02:31

2 Answers2

3

try this

handleShow = element => this.setState({
    ...this.state, 
    [element]: true
});
iamhuynq
  • 5,357
  • 1
  • 13
  • 36
  • My question is more related to 'element' here. I am passing state variable as string eg: "showLogin", "showHome" but it not working. How can I pass the name of the state variable dynamically? – Avi Mar 23 '20 at 09:41
1

In your handler method, you must use spread operator, this allow you create a clone of your state and thus concatenate a new value.

Handler Method

handleShow = (element) => this.setState({ ...this.state, [element]: true });