简体   繁体   中英

on clicking button, change classname of the clicked button as well as other buttons in that group using reactjs

I have a react component with 3 buttons. On click of any of the buttons in the group, the class name should be appended with 'active' for that button alone. Rest of the two buttons should not have 'active' in their class names. Can some one help me with this scenario. I am new to React. I am not sure how the 'active' can be added/removed for each button. Please help.

state={
  active:false, 
 }

handleEnvClick() {
    console.log(this.state.active)
    this.setState=({
     active:true,
   })
}


<div className="EnvGroupButtonsMain">
<button onClick={() => this.handleEnvClick("Dev")} className="envButton">Dev</button>
<button onClick={()=>this.handleEnvClick("QA")} className="envButton">QA</button>
<button onClick={()=>this.handleEnvClick("Prod")} className="envButton">Prod</button>
</div>
state={
  selectedButton:""
 }

handleEnvClick(selectedButton) {
    this.setState=({
    selectedButton:selectedButton
   })
}


<div className="EnvGroupButtonsMain">
<button onClick={() => this.handleEnvClick("dev")} className={`${this.state.selectedButton==='dev'?'activeEnv':'inActiveEnv'}`}>Dev</button>
<button onClick={()=>this.handleEnvClick("qa")} className={`${this.state.selectedButton==='qa'?'activeEnv':'inActiveEnv'}`}>QA</button>
<button onClick={()=>this.handleEnvClick("prod")} className={`${this.state.selectedButton==='prod'?'activeEnv':'inActiveEnv'}`}>Prod</button>
</div>

You can now have following in your style sheet:-

.activeEnv{
//custom css
}
.inActiveEnv{
//custom css
}

Btw ${variable} are template literals in case you were not aware. They are cool:D.

You can do something like this:

state={
  activeButton: 0, 
 }

handleEnvClick(clicked) {
    console.log(this.state.active)
    let active = 0;
    if(clicked == "Dev")
      active = 1;
    if(clicked == "QA")
      active = 1;
    if(clicked == "Prod")
      active = 1;
    this.setState=({
     activeButton:active,
   })
}


<div className="EnvGroupButtonsMain">
<button  onClick={() => this.handleEnvClick("Dev")} className="{envButton "+(this.state.activeButton == 1? "active":"")}>Dev</button>
<button onClick={()=>this.handleEnvClick("QA")} className="envButton "+(this.state.activeButton == 2? "active":"")>QA</button>
<button onClick={()=>this.handleEnvClick("Prod")} className="envButton "+(this.state.activeButton == 3? "active":"")>Prod</button>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM