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.

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:

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.