I’m doing Blogvent, a challenge to blog every day through December 25th. Today’s prompt is:

Day 6: One dependency you always install. Spotlight a small, reliable library you reach for across projects and explain why it beats writing it from scratch.

Classnames is a library I always end up installing.

Classnames lets you build HTML classes with a simple, intuitive interface:

const classNames = require('classnames');

classNames('foo', 'bar'); // => 'foo bar'

I see components like this often in older codebases:

type Props = {className?: string; wrapperClassName?: string};

const Component = ({className = '', wrapperClassName = ''}: Props) => {
  return (
    <div className={`title ${className} ${wrapperClassName}`}>Welcome!</div>
  );
};

Both props are optional and default to empty strings. If we pass className and omit wrapperClassName, the rendered class attribute has a trailing space:

<Component className="featured" />
// Renders class="title featured "

Untidy! Classnames omits empty strings:

classNames('title', 'featured', ''); // => 'title featured'

I reach for it when I need to add a class conditionally, too:

const isFeatured = true;

classNames('title', {featured: isFeatured}); // => 'title featured'

Here’s the same thing with a template literal:

<div className={`title ${isFeatured ? 'featured' : ''}`}>Welcome!</div>

When isFeatured is false, there’s that trailing space again. I’d rather learn one interface I can use in a variety of cases than hand-code it every time.