clsx Utility
clsx is a tiny (239 bytes) utility for constructing className
strings conditionally in JavaScript. It serves as a faster and smaller drop-in replacement for the classnames module, making it a preferred choice for performance-conscious developers.
Installation
$ npm install --save clsx
Usage
The clsx utility can be used to conditionally combine class names from various sources such as strings, objects, arrays, and even nested structures. Here are some examples:
import clsx from 'clsx';
// or
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'
API
The clsx function can take any number of arguments, each of which can be an object, array, boolean, or string. Important: Any falsy values are discarded. Standalone boolean values are discarded as well.
clsx(true, false, '', null, undefined, 0, NaN);
//=> ''
Advantages
The clsx utility has several advantages:
- ✨ Lightweight: At just 239 bytes, it has a minimal footprint, making it ideal for performance-focused applications.
- ⚡ Fast: It's designed to be fast, offering better performance compared to other similar utilities.
- 🛠️ Flexible: It accepts various input types (strings, objects, arrays), making it versatile for different use cases.
- 📦 Modular: There are multiple versions available (default, lite), allowing developers to choose the functionality they need without extra bloat.
- 🌐 Broad Support: It supports all versions of Node.js and all browsers that support
Array.isArray
(IE9+).
Modes
There are multiple "versions" of clsx available, which allows you to bring only the functionality you need:
- clsx: The default module, available as CommonJS, ES Module, and UMD.
- clsx/lite: Accepts only string arguments; useful within Tailwind contexts. Any non-string arguments are ignored.
For example:
import { clsx } from 'clsx/lite';
// or
import clsx from 'clsx/lite';
// string
clsx('hello', true && 'foo', false && 'bar');
//=> "hello foo"
// Note: Any non-string input(s) ignored
clsx({ foo: true });
//=> ""
Support
All versions of Node.js are supported. All browsers that support Array.isArray
are supported (IE9+).
Post a Comment
0Comments