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.

Improve your React Skills!

Learn about React concepts, helpful libraries or get tips & tricks for deploying your app and many more topics.

I semi regularly post about React. Don't miss out on my future posts! Sign up below to get them delivered directly into your inbox!

14 thoughts on “How to dynamically add CSS Classes to React Elements using State”

      1. Andreas, you are a class act. Thank you for the code example. I am able to use it. Also, in programming writing, replace the phrase “cheat sheet” with “reference document.” It is professional. Nobody is cheating to look things up!

        1. Hi John, thanks for the feedback!
          I didn’t look at it that way, I felt cheatsheet is a commonly used term – I’ll keep it in mind for the future 🙂

          Cheers,
          Andreas

  1. Thank you, this guide is so helpful. I have two questions though:
    – Shouldn’t there be a second backtick in this code:

    <

    div className={`box ${isBoxVisible ? “” : ” hidden”}}>
    – In the code above, if the box is hidden, another class named “hidden” will be added to the div. The div will have two classes: box and hidden. By the way you write the code, there will be double space between class name “box” and class name “hidden”, right? Because there is a space after the “box”, before the dollar sign $, and another space before “hidden”.

    1. Hi! Thanks for the feedback, you’re right, I was missing the closing backtick, thank you for pointing this out.
      I also removed the second whitespace between the classes “box” and “hidden”.

      1. Hi Andreas, isBoxVisible in the return statement of the render method should read this.state.isBoxVisible.

        1. Hi John!

          A few lines above, I put const { isBoxVisible } = this.state; – which does basically the same as const isBoxVisible = this.state.isBoxVisible.
          In my opinion, it makes the code a bit more readable.
          Without that statement, you’re right – it should be this.state.isBoxVisible

          Cheers,
          Andreas

  2. You can use classnames for react (https://www.npmjs.com/package/classnames)
    in a manner like this:
    var Button = React.createClass({
    // …
    render () {
    var btnClass = classNames({
    btn: true,
    ‘btn-pressed’: this.state.isPressed,
    ‘btn-over’: !this.state.isPressed && this.state.isHovered
    });
    return {this.props.label};
    }
    });

    1. This would work quite the same – in the event handle of your desired event (e.g. mouse move or onClick, etc) you set the state of your component.
      So that’s where you would trigger your custom logic and store the necessary information in your component’s state.
      Similar to my example, you would access this info (e.g. width or something else) and build a CSS Style Object style={{width: "120"}} instead of a className

  3. The order of your closing back-tick and a closing curly bracket are switched in your code. It should be }`}. The first curly closes the ‘if’ statement, the back-tick closes the string, then the second curly closes the className.

    But great tutorial, it really helped me to understand the concept.

    1. Just fixed that – things like that are easy to miss in the editor of my website where I have no code highlighting 😀

      thanks for the feedback, I’m glad to help!

  4. This line in the code block is wrong:

    <

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

    The ending back-tick should be between the curly braces, not before them.

Leave a Reply

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