Skip to content

clsx

clsx is a utility for constructing className strings conditionally. It is often used in conjunction with Tailwind CSS to apply styles based on certain conditions.

js
import clsx from "clsx";

const buttonClass = clsx(
  "px-4 py-2 rounded",
  {
    "bg-blue-500 text-white": isPrimary,
    "bg-gray-200 text-gray-800": !isPrimary,
  },
  {
    "hover:bg-blue-600": isPrimary,
    "hover:bg-gray-300": !isPrimary,
  }
);

Falsy values

clsx treats falsy values (like false, null, undefined, 0, and '') as not contributing to the className string. This allows for cleaner conditional logic without cluttering the output with unnecessary classes.

js
const isActive = false;
const className = clsx(
  "base-class",
  isActive && "active-class",
  null, // This will not contribute to the className
  undefined, // This will also not contribute
  0, // This will not contribute either
  "" // An empty string will not contribute
);
// className will be 'base-class'