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:

[code]
<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>
[/code]

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.

[javascript]
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>;
}

[/javascript]

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.

[javascript]
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>
);
}
[/javascript]

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.

[javascript]
var classNames = require( ‘classnames’ );
[/javascript]

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.

[javascript]
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>
);
}
[/javascript]

Comments

7 responses to “Dynamically Add Classes with React classSet”

  1. badedyrRasmus Avatar
    badedyrRasmus

    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 ?

  2. Rui Nunes (@ruinunesdev) Avatar

    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.

  3. Puneet Avatar

    I am trying to change background color of a row of table according to the data it is showing. Eg- if status is successful its color should be green.
    How can I do that?

  4. Justin Lindsay Avatar
    Justin Lindsay

    Why install a dependency and scatter a whole bunch of import statements when you can just do this:

    var classes = [
    this.props.className,
    (this.active==’yes’) ? “active” : ”
    etc..
    ].join(‘ ‘)

  5. Justin Lindsay Avatar
    Justin Lindsay

    Sorry couldn’t edit…

    Better yet, you could even do this

    var classes = [
    this.props.className,
    this.active ? active : ”
    etc..
    ].join( )

    1. Eric Binnion Avatar

      That looks reasonable to me, and is a bit cleaner than my first approach at dynamic classes that I mention above. I think the way that classnames handles it is a bit simpler to read since it doesn’t use ternaries and object keys are the possible classes that could get added to the string.

      _(?)_/

Leave a Reply to Justin LindsayCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading