Note: React.addons.classSet is now deprecated and you should use classnames. There is an explanation of how to use classnames at the end of the article.

Earlier today, I needed to add some classes to a link. One class was passed in through a prop, but the other class would be added based on a boolean condition.

It’s simple to access props within a React component, so my first crack at setting the classes looked something like this:

<li className={ this.props.className }>
    <a
        href={ this.props.href }
        onClick={ this.setLayoutFocus }
        className={ this.props.selected === this.props.className ? 'selected ' + this.props.className : this.props.className } >
            <span className="menu-link-text">{ this.props.label }</span>
    </a>
</li>

Eww… check out that nasty looking ternary.

Good thing for pull requests, because that one was denied pretty quickly. In the pull request feedback, Beau Lebens mentioned that there was a CSS utility included with React called classSet.

He mentioned that the React classSet utility would be helpful because I’d be able to build my classes string without having to have a bunch of conditional statements and string concatenation. #winning

So, I went Googling and figured out how to use the React classSet utility. Here’s the relevant documentation for using React’s classSet for class name manipulation.

Here’s an example of how the React classSet utility works from the documentation linked above.

render: function() {
    var cx = React.addons.classSet;
    var classes = cx({
        'message': true,
        'message-important': this.props.isImportant,
        'message-read': this.props.isRead
    });
    // same final string, but much cleaner
    return <div className={classes}>Great, I'll be there.</div>;
}

This is a simple example, but what about the case where the class is passed in via a prop as opposed to just being switched on or off by a boolean?

Second Try with React classSet

This try at adding classes via the React classSet utility allows us to add a class that is passed in via a prop.

render: function() {
    var classes = React.addons.classSet({
        'selected': ( this.props.selected === this.props.className )
    });

    /*
     * Since the className changes from sidebar item to item,
     * we dynamically add this sidebar item's class as a key.
     */
    classes[ this.props.className ] = true;

    return (
        <li className={ classes }>
            <a href={ this.props.href } onClick={ this.setLayoutFocus } >
                 <span className="menu-link-text">{ this.props.label }</span>
            </a>
        </li>
    );
}

Note that in this second try that we are dynamically appending our class that was passed in via the className prop to the classes object.

Then, when we call className={ classes } our string of classes is created.

Using classnames instead of classSet

React has deprecated React.addons.classSet and has suggested that developers use the classnames node module instead.

So, first things first, you’ll want to install classnames. You can usually do this in the root of your project, and you’ll use this command: npm install classnames.

Once you have installed classnames, you will then need to require it in your JSX file.

var classNames = require( 'classnames' );

Once we have required classnames, we should be able to simply swap out React.addons.classSet with classNames. Even better though, since classnames is so robust, we can just pass in this.props.className as an argument.

render: function() {
    var classes = classNames( this.props.className, {
        'selected': ( this.props.selected === this.props.className )
    } );

    return (
        <li className={ classes }>
            <a href={ this.props.href } onClick={ this.setLayoutFocus } >
                 <span className="menu-link-text">{ this.props.label }</span>
            </a>
        </li>
    );
}

3 thoughts on “Dynamically Add Classes with React classSet

  1. How would this look if i wanted to dynamically set the className on a component in a list?
    I am trying to understand how i would add the class ‘active’ to a component that is clicked in a list.
    i have this in my child component:

    var className = this.props.isActive ? ‘list-group-item active’ : ‘list-group-item’;

    and i control that prop through state in the parent, but i dont understand how i would pick the component child that is being clicked to set the state individually ?

    1. Hello there,

      I know that in WordPress.com Calypso, we often decide which section is selected by the path. Take this for example: https://github.com/Automattic/wp-calypso/blob/master/client/my-sites/people/people-section-nav/index.jsx#L35-L53

      Note how we send a boolean prop that is labeled selected to the NavItem component. This boolean is decided by comparing the id of a menu item to the filter parameter from the path.

      Hopefully this example helps.

  2. You could do something like
    const classNames = [‘someClassName1’, isSomething ? ‘someClass2’ : ”].filter(Boolean).join(‘ ‘)
    But I think concatenating strings at the expense of a blank space in a class attribute is better.

Leave a Reply