A closer look at the ClassNames npm package

Looking at a useful package that all teams using React should be familiar with.

photo of Andra Joy Lally
Andra Joy Lally

Full Stack Developer

Posted on Aug 11, 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 (

                TEXT

        )
    }

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 (

TEXT

        )
    }

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.


We're hiring! Do you like working in an ever evolving organization such as Zalando? Consider joining our teams as a Frontend Engineer!



Related posts