How to dynamically add CSS Classes to React Elements using State

If you’re just starting out with React, you might soon get to the point where you want to dynamically change the styling of some React Elements – e.g. at the click of a button. In this post we have a closer look at this concept. 

Manipulating CSS classes of elements doesn’t sound like a problem if you’re familiar with jQuery. But you might wonder how you can dynamically add or remove classes to React Elements.

Maybe you already found out that you can use the component’s state, but you still don’t know exactly how the state plays together with styling and rendering your elements.

Let’s have a walk through this concept. I put together a little example, where we show and hide a box with the click of a button.

Initial State

First of all, we need to track if our box is currently visible or hidden. That’s what a component’s state is for. It stores all the information that can change within this component.

At the beginning, we initialize our state object. It has a boolean value isBoxVisible that is initially set to false.

state = {
  isBoxVisible:false
};

Reacting to User Interactions

Next, let’s take a look at our button within our render function. Whenever the user clicks our button, it will toggle the boolean value for isBoxVisible. As you can see, we pass our toggleBox function to the button’s onClick event. Each time the button is pressed, it will toggle the boolean value for isBoxVisible in the component’s state.

toggleBox = () => {
  this.setState(prevState => ({ isBoxVisible: !prevState.isBoxVisible }));
};

render() {
  return (
    <div className="App">
      <button onClick={this.toggleBox}>Show Box</button>

      [...]
    </div>
  );
}

Dynamically changing CSS classes

When the state of a component changes, React performs a re-render. So we can react to state changes within our render function. This is the point where we pass the respective CSS classes to our box.

render() {
  const { isBoxVisible } = this.state;

  return (
    <div className="App">
      <button onClick={this.toggleBox}>Show Box</button>

      <div className={`box ${isBoxVisible ? "" : " hidden"}}>
        <p>I'm the box</p>
      </div>

    </div>
  );
}

As you can see, at the top of our render function, we get isBoxVisible from the component’s state. Within our Markup, you can see that we pass the className information to our box div, depending on the state of isBoxVisible:

<div className={`box ${isBoxVisible ? "" : " hidden"}}>

Instead of just a string with the class name, we can pass an expression. This expression is evaluated each time the component is rendered. For short expressions I prefer the short hand syntax like in this example, but you could also just call a function that returns the right class names:

<div className={this.getBoxClassNames()}>

Wrapping Up

In this article you learned, how to use the component’s state to track the display information of an element and how to use this information to dynamically change the CSS classes for this element.

Keep in mind that you can use this concept for more than just styling purposes.  What you’ve learned today is a core concept of React: Some action changes the component state (e.g. a user interaction, data being fetched from server) and within the render function we take care to display the respective elements – according to the current state.

If you don’t feel that comfortable with the component’s state yet, head over to the official docs and get a feeling how it is used correctly. If things are still unclear, leave a comment and I’ll be glad to help.

[signup-form]

Leave a Reply