how to change classes on clicking in react?

Viewed 136

Here is the code:

state: {
    button: "notclicked"
}

changeclass = () => {
    this.setState({ button: "clicked" })
} 

<ul>  
    <li className="linkactive">
        <a class="vote-up-off" onClick={ this.changeclass } href="/">
            <Icon className={ this.state.button } className=" fa fa-area-chart"/>
        </a>
    </li>
    <li>
        <a class="vote-up-off"href="/">
            <Icon className="fa fa-bar-chart fa-2x"/> 
        </a>
    </li>
    <li>
        <a class="vote-up-off" href="/>
            <Icon className="fa fa-line-chart"/>
        </a>
    </li>
</ul>

I am able to change the class on clicking <li>, But on clicking another <li>, how to make prev class back to notclicked?

I want to show the user which tab he is currently on

2 Answers

What happen now with your changeClass() function is that every time you click on the link, the state.button is set to "clicked".

What you could do in this method is start by checking the value of button and set it to the other value. eg:

changeclass=()=>{
    if(this.state.button === "notclicked"){
      this.setState({button:"clicked"}) 
  }
    else {
      this.setState({button:"notclicked"})
  }

} 

Then, if you want each <li> to trigger your changeclass function, onClick must be set for each one of them.

Also, there are a few typos in your code:

  • onClicke must be onClick
  • in the last <a> tag, the string besides href is not closed (there is a missing ")

To summarize, this code should work as expected:

state:{
button:"notclicked"
}

changeclass = () => {
    if(this.state.button === "notclicked"){
      this.setState({button:"clicked"}) 
  }
    else {
      this.setState({button:"notclicked"})
  }

} 

<ul>
             
    <li className="linkactive"><a class="vote-up-off" onClick={this.changeclass} href="/"><Icon className={this.state.button} className=" fa fa-area-chart"/></a></li>
     <li><a class="vote-up-off"href="/" onClick={this.changeclass}><Icon className="fa fa-bar-chart fa-2x"/></a></li>
    <li><a class="vote-up-off" href="/" onClick={this.changeclass}><Icon className="fa fa-line-chart"/></a></li>   

</ul>

you can try it like this

// lets assume initial state is false
state = {clicked : false}

later on your component, you make ternary if by doing it like this

changeClicked = ()=>{
  // this setState will take what you have previously, and
  // will change it to opposite value
  this.setState(prev=>({clicked: !prev.clicked}))
}

//...

<a onClick={this.changeClicked}>
  <Icon className={clicked ? "clicked":"notclicked"} />
</a>

my suggestion is if you have something opposite like clicked-notclicked, on-off, up-down, etc that inherently one will always be true when the opposite is false, use boolean.

it will help you down the road.

Related