A closer look at the ClassNames npm package

by Andra Joy Lally - 11 Aug 2016

The newest tool sweeping through the React teams here at Zalando Tech is the classNames npm package. The concept is simple and deletes countless lines of unneeded code, on top of increasing readability.

The first time I heard about this useful package was at an All Hands meeting, where tech teams can share what what they are doing with their product. It allows engineers to share new knowledge in a shorter period of time. The ideas or tools shared do not have to be profound, but they do have to improve the development process of our teams.

One of React’s features is to write a conditional that will return one classname over another or no class at all. Below is an example:

Before:

  render() {
const {
isActive,
isHidden,
index
} = this.props
const hiddenClass = active ? ‘isActive’ : ‘’;
const activeClass = isHidden ? ‘isHidden’ : ‘’;
const fadeInClass = index ? `fade-in-${index}` : ‘’;
(etc class conditionals …)
return (
<div className={`${fadeInClass} ${hiddenClass} ${activeClass} other-class-name`}>
TEXT
</div>
)
}

After:

  render() {
const {
isActive,
isHidden
} = this.props
const containerClasses = classNames( ‘other-class-name’, {‘isHidden’: isHidden}, {‘isActive’: isActive}, {‘index’: `fade-in-${index}` }, (etc class conditionals …));
return (
<div className={containerClasses}>
TEXT
</div>
)
}

I’m also using the new string interpolation feature and have added JavaScript to the code above. If you are not using this new feature, you should start today!

Instead of having endless conditionals on the top of your React render method, you have it nicely cleaned up to one line that is easy to read and reason through.

While this package is not the most profound invention in the React community, it is incredibly helpful and deletes unneeded lines of code. The increase of readability between team members is also a big plus. If you are not using it at the moment I encourage looking at the documentation and add it to your current project.

Want to know how I added it to mine? Contact me at andra.joy.lally@zalando.de with your questions.

Similar blog posts