Ian Springer Ian Springer -4 years ago 160
CSS Question

Add class when button clicked in react.js

I've been working on React for a few weeks now, and while I've got most of the basic syntax down (props, states), I'm struggling to draw some connections with some concepts, most notably adding classes when a state has changed. I'm trying to build a simon says game, which contains four buttons, all built using a Button component. These are initially set to have a opacity of .3 and an active state of false. When clicked, the state "active" becomes true, but I cannot for the life of me figure out how to add a css class that can give the button a full opacity. Here is my code:

class App extends Component {
this.state = {
active: false
this.setState({active: !this.state.active})
renderButtons(i, f){
return <Button value={i} className="button" id={f} active= {this.state.active} onClick={() => this.handleClick()}/>
render() {
return (
<div className="App">
{this.renderButtons("red", "buttonRed")}
{this.renderButtons("blue", "buttonBlue")}
{this.renderButtons("green", "buttonGreen")}
{this.renderButtons("yellow", "buttonYellow")}

And my css:

width: 100px;
height: 45px;
opacity: .3;
margin: 0 auto;
margin-bottom: 30px;
background: red;
background: blue;
background: green;
background: yellow;

So, at this moment, I would simply like to add a class when clicking the button while still keeping the "button" class to the component. Can anyone help?

Answer Source

React has a couple of ways of doing this. The first is as suggested by Tudor Ilisoi, which is simply concatenating strings. The second way is to give className an Object instead of a string.

<button className={{button: true, active: this.state.active}} />

The double {{ is because we are passing an Object. The first pair of curly brackets just tells react that we are passing a dynamic property, and the second is just the normal JavaScript syntax for objects. If we had declared it earlier, we could just as easily do

    const classes = {
        button: true, // we always want this class
        active: this.state.active, // only add this class if the state says so
     return (
          <button className={classes} />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download