Working with React joinClasses

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

React has slowly been coming together for me over the past few weeks as I have slowly moved from “how do I get this thing to work?” to “how can I factor this out?” mindset.

As I’ve slowly ventured into composition with React, one of the pain points that I’ve had was elegantly concatenating classes.

After a tip from Beau and some searching, my first try at concatenating classes in React was done using the classSet utility. And while I was able to use classSet to concatenate classes in a React component, I didn’t find it to be a very elegant or easily readable solution.

A bit more searching led me to a utility named joinClasses.

Using React joinClasses to Concatenate Class Names

Here is an example of how I am using joinClasses to concatenate CSS classes in a React component.

var React = require( 'react' ),
    joinClasses = require( 'react/lib/joinClasses' );

module.exports = React.createClass( {

    render: function() {
        var selected = ( this.props.selected === this.props.className ? 'selected' : '' );

        return (
            <li className={ joinClasses( this.props.className, selected ) } >
                <a href={ this.props.href }> { this.props.label }</a>
            </li>
        );
    }
} );

this.props.selected above is a string that represents which sidebar link should be selected and this.props.className is the class of the current sidebar link.

If the two match, then we want to add a class of selected to the sidebar item along with any classes that were passed in this.props.className.

If there were more classes to be conditionally added based on props that were passed in, I would look into combining the classSet utility along with the joinClasses utility.

Using classnames instead of joinClasses

React has deprecated joinClasses 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. Note, you might want to use npm install --save-dev classnames in order to update your package.json file.

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 joinClasses with classNames. Here’s an updated example:

var React = require( 'react' ),
    classNames = require( 'classnames' );

module.exports = React.createClass( {

    render: function() {
        var selected = ( this.props.selected === this.props.className ? 'selected' : '' );

        return (
            <li className={ classNames( this.props.className, selected ) } >
                <a href={ this.props.href }> { this.props.label }</a>
            </li>
        );
    }
} );

Also, because classnames is so robust and will allow us to send an object to it, we can simplify the code a bit:

var React = require( 'react' ),
    classNames = require( 'classnames' );

module.exports = React.createClass( {

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

        return (
            <li className={ classNames( this.props.className, selected ) } >
                <a href={ this.props.href }> { this.props.label }</a>
            </li>
        );
    }
} );

Dynamically Add Classes with React classSet

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>
    );
}