clsx is a tiny (239B) utility for constructing className strings conditionally. It serves as a faster and smaller drop-in replacement for the popular classnames module, supporting various input types including strings, objects, arrays, and booleans while automatically filtering out falsy values.
npm install clsxES Module (default):
import clsx from "clsx";ES Module (named):
import { clsx } from "clsx";CommonJS:
const clsx = require("clsx");Lite version (string-only):
import clsx from "clsx/lite";
// or
import { clsx } from "clsx/lite";import clsx from 'clsx';
// Strings (variadic)
clsx('foo', true && 'bar', 'baz');
//=> 'foo bar baz'
// Objects
clsx({ foo: true, bar: false, baz: isTrue() });
//=> 'foo baz'
// Arrays
clsx(['foo', 0, false, 'bar']);
//=> 'foo bar'
// Mixed arguments (kitchen sink)
clsx('foo', [1 && 'bar', { baz: false, bat: null }, ['hello', ['world']]], 'cya');
//=> 'foo bar hello world cya'The primary function that accepts any number of arguments of various types and returns a consolidated className string.
function clsx(...inputs: ClassValue[]): string;Arguments:
inputs - Any number of ClassValue arguments (strings, numbers, booleans, objects, arrays, null, undefined)Returns:
string - Consolidated className string with space-separated class namesBehavior:
A lightweight variant that only processes string arguments, ignoring all other input types.
function clsx(...inputs: string[]): string;Arguments:
inputs - Any number of string arguments (non-string arguments are ignored)Returns:
string - Consolidated className string from valid string inputs onlyUsage:
import clsx from 'clsx/lite';
// Only strings are processed
clsx('hello', true && 'foo', false && 'bar');
//=> "hello foo"
// Non-string inputs are ignored
clsx({ foo: true }, ['bar'], 42);
//=> ""type ClassValue = ClassArray | ClassDictionary | string | number | bigint | null | boolean | undefined;
type ClassDictionary = Record<string, any>;
type ClassArray = ClassValue[];Type Descriptions:
ClassValue - Union type representing all valid input types for clsxClassDictionary - Object type where keys are class names and values determine inclusionClassArray - Recursive array type allowing nested ClassValue itemscondition && 'class-name'clsx('base-class', {
'active': isActive,
'disabled': !isEnabled,
'error': hasError
});clsx(
'always-present',
condition && 'conditional-class',
{
'object-based': someBoolean,
'another-class': anotherCondition
},
['array', 'classes', nested && 'nested-class']
);function Button({ variant, size, disabled, className, children }) {
return (
<button
className={clsx(
'btn',
`btn-${variant}`,
`btn-${size}`,
{
'btn-disabled': disabled
},
className
)}
>
{children}
</button>
);
}// Optimal for Tailwind with clsx/lite
import clsx from 'clsx/lite';
const classes = clsx(
'text-base',
props.active && 'text-primary',
props.className
);dist/clsx.jsdist/clsx.mjsdist/clsx.min.jsdist/lite.jsdist/lite.mjsclsx is designed to be fault-tolerant: