Conditional CSS Class Utility

2.5.1 · active · verified Sun Apr 19

The `classnames` utility simplifies the conditional joining of CSS class names in JavaScript and TypeScript applications. It accepts any number of arguments, including strings, objects (where keys are class names and values are booleans), and arrays, intelligently combining them into a single, space-separated string. The package is currently at version 2.5.1, following the SemVer standard, indicating a strong commitment to stability and backwards compatibility for minor and patch releases. It is widely adopted, especially within the React ecosystem, due to its robust performance and minimalist API. Its key differentiators include its extreme stability, thorough test suite, and focus on performance, ensuring it reliably handles class name generation in high-frequency scenarios across browsers and Node.js environments. The project's philosophy emphasizes speed and stability, with updates thoroughly reviewed for performance implications.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates various ways to combine class names, including static strings, conditional objects, arrays, and dynamic class names, handling falsy values gracefully.

import classNames from 'classnames';

const isActive = true;
const hasError = false;
const theme = 'dark';

// Basic usage with strings
const classes1 = classNames('container', 'header');
console.log(classes1); // Expected: 'container header'

// Conditional classes using objects
const classes2 = classNames('button', {
  'button--primary': isActive,
  'button--danger': hasError,
  [`theme-${theme}`]: true // Dynamic class name based on variable
});
console.log(classes2); // Expected: 'button button--primary theme-dark'

// Mixing strings, objects, and arrays
const classes3 = classNames(
  'card',
  { 'card--active': isActive },
  ['shadow', 'rounded'],
  null,
  undefined,
  { 'card--hidden': !isActive }
);
console.log(classes3); // Expected: 'card card--active shadow rounded'

view raw JSON →