A tiny (200B) utility for constructing
className
strings conditionally.
Also serves as a faster & smaller drop-in replacement for theclassnames
module.
This module is available in three formats:
- ES Module:
dist/clsx.mjs
- CommonJS:
dist/clsx.js
- UMD:
dist/clsx.min.js
$ npm install --save clsx
import clsx from 'clsx';
// Strings (variadic)
clsx('foo', true && 'bar', 'baz');
//=> 'foo bar baz'
// Objects
clsx({ foo:true, bar:false, baz:isTrue() });
//=> 'foo baz'
// Objects (variadic)
clsx({ foo:true }, { bar:false }, null, { '--foobar':'hello' });
//=> 'foo --foobar'
// Arrays
clsx(['foo', 0, false, 'bar']);
//=> 'foo bar'
// Arrays (variadic)
clsx(['foo'], ['', 0, false, 'bar'], [['baz', [['hello'], 'there']]]);
//=> 'foo bar baz hello there'
// Kitchen sink (with nesting)
clsx('foo', [1 && 'bar', { baz:false, bat:null }, ['hello', ['world']]], 'cya');
//=> 'foo bar hello world cya'
Returns: String
Type: Mixed
The clsx
function can take any number of arguments, each of which can be an Object, Array, Boolean, or String.
Important: Any falsey values are discarded!
Standalone Boolean values are discarded as well.
clxs(true, false, '', null, undefined, 0, NaN);
//=> ''
For snapshots of cross-browser results, check out the bench
directory~!
- obj-str - Similar utility that is faster and smaller (100B) but only works with Objects.
MIT © Luke Edwards