Filipe
Filipe

Reputation: 61

How can I toggle between states of a button in React?

I'm using Material UI for the icons for connect and disconnect. I want the application to swap between these two icons onClick. I'm new to React, but haven't any helpful resources yet. Here's the code as it is so far:

 { user.connected ? 
    (
    <Button color="info" simple size="sm">
      <PersonAddDisabled className={classes.footerIcons} /> Disconnect
    </Button> 
    )
    : 
    (
     <Button color="info" size="sm">
        <PersonAdd className={classes.footerIcons} /> Connect
     </Button> 
    )
}

As it is above, I am address whether they are connected or not, but I'm not sure how to implement a toggle of those two buttons, where onClick it will switch between the two.

Upvotes: 0

Views: 476

Answers (1)

Alex
Alex

Reputation: 838

here is a code Your state

 state = {
    connected: true
 }

 onClickButton(){      
   this.setState(prevState => {connected: !this.prevState.connected}) 
 }

Your code

{ this.state.connected ? 
  (
  <Button color="info" simple size="sm" onClick={ this.onClickButton }>
   <PersonAddDisabled className={ classes.footerIcons } /> Disconnect
  </Button> 
  )
  : 
  (
  <Button color="info" size="sm" onClick={ this.onClickButton }>
    <PersonAdd className={ classes.footerIcons } /> Connect
  </Button> 
  )
}

Upvotes: 2

Related Questions