How To Add A Class in ReactJS

March 14, 2018

What's the best way to add a class in ReactJS? With Jquery, we're all familiar with:

$("#foo").addClass("bar");

So what's the analogue for this in ReactJS?

How NOT To Add A Class in ReactJS

You can do stuff like:

<div className={this.state.toggle ? 'foo' : 'foo bar'}></div>

But this approach is clunky because we want to add a class - not just change the classes from "foo" to "foo bar". Functionally there's little difference in this simple case but you can imagine this approach would not be ideal when you have elements with a lot of classes.

Adding Classes With push and join

The push() method adds one or more elements to the end of an array. In the example below, the array is box.

The join() method joins all elements of an array into a string.

...
let box = ["foo"];
render() {
  if(this.state.addClass) {
    box.push("bar");
  }
  return(
    <div className={box.join('' )} />
  );
}
...

In this example, we made the addition of the new class bar dependent on this.state.addClass. Presumably you'd have some action like an onClick event to trigger a state change.

The Complete, Working Example