← Back to archive

Repo of the Day

lukeed/clsx

Published: Feb 11, 2023

Open repository ↗

A tiny (228B) utility for constructing className strings conditionally.

Summary

clsx is a small JavaScript utility (239 bytes gzipped) that builds CSS className strings by combining strings, objects, and arrays while filtering out falsy values. The README describes it as a faster and smaller drop-in replacement for the classnames module. It is published under the MIT license and ships as CommonJS, ES Module, and UMD builds.

What it is useful for

clsx is useful whenever you need to assemble a className from several optional or conditional pieces, which is common in React, Preact, Vue, or plain DOM code. It accepts every input shape component code already uses: variadic strings, plain objects whose keys are class names, nested arrays, and any mix of them. Falsy values (false, 0, null, undefined, '', NaN) are discarded, so you can inline boolean expressions without manually guarding them.

This makes it handy for toggling active or disabled states, appending a user-supplied className prop, and composing utility-class frameworks like Tailwind CSS. The README includes a Tailwind IntelliSense configuration for Visual Studio Code so clsx(...) calls participate in class autocompletion.

A documented limitation: standalone boolean values are discarded, and the clsx/lite build only accepts string arguments. Non-string inputs to clsx/lite are silently ignored, so the lite variant is only safe when your callsites already follow the string-builder pattern.

How engineers can use it

Install via the documented command:

$ npm install --save clsx

Then import and use it in a component:

import clsx from 'clsx';

function Button({ active, disabled, className }) {
  return (
    <button
      className={clsx(
        'btn',
        { 'btn-active': active, 'btn-disabled': disabled },
        className
      )}
    />
  );
}

Object form reads naturally for state flags:

clsx({ foo: true, bar: false, baz: isTrue() });
// => 'foo baz'

Arrays can be nested and combined variadically, and falsy entries are skipped:

clsx(['foo', 0, false, 'bar'], [['baz', [['hello'], 'there']]]);
// => 'foo bar baz hello there'

If your codebase only concatenates string fragments, switching to clsx/lite (140 bytes gzipped) keeps the same call shape at a smaller size, but you must avoid passing objects or arrays to it. Browser support covers IE9+; for IE8, the README points to [email protected].