< Back to Coding, React

Conditional classes and toggling state

Here’s a basic example:

<div className={`defaultClass ${this.state.con1 ? "con1" : ""} 
${this.state.con2 ? "con2" : ""}`}>
  something
</div>

And you can toggle the state like so:

handleClick(e){
    this.setState(prevState => ({
      con1: !prevState.con1
    })
    );
  }

Demo here.

Leave a Reply

Your email address will not be published. Required fields are marked *