SRIKANTH D
SRIKANTH D

Reputation: 39

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>

Upvotes: 0

Views: 372

Answers (2)

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

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.

Upvotes: 1

Hamza Arshad
Hamza Arshad

Reputation: 846

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>

Upvotes: 0

Related Questions