clsx

A tiny (228B) utility for constructing `className` strings conditionally.

README

clsx CI codecov


A tiny (228B) utility for constructing className strings conditionally.<Br>Also serves as a faster & smaller drop-in replacement for theclassnames module.


This module is available in three formats:

ES Module: dist/clsx.m.js
CommonJS: dist/clsx.js
UMD: dist/clsx.min.js


Install


  1. ```
  2. $ npm install --save clsx
  3. ```


Usage


  1. ```js
  2. import clsx from 'clsx';
  3. // or
  4. import { clsx } from 'clsx';

  5. // Strings (variadic)
  6. clsx('foo', true && 'bar', 'baz');
  7. //=> 'foo bar baz'

  8. // Objects
  9. clsx({ foo:true, bar:false, baz:isTrue() });
  10. //=> 'foo baz'

  11. // Objects (variadic)
  12. clsx({ foo:true }, { bar:false }, null, { '--foobar':'hello' });
  13. //=> 'foo --foobar'

  14. // Arrays
  15. clsx(['foo', 0, false, 'bar']);
  16. //=> 'foo bar'

  17. // Arrays (variadic)
  18. clsx(['foo'], ['', 0, false, 'bar'], [['baz', [['hello'], 'there']]]);
  19. //=> 'foo bar baz hello there'

  20. // Kitchen sink (with nesting)
  21. clsx('foo', [1 && 'bar', { baz:false, bat:null }, ['hello', ['world']]], 'cya');
  22. //=> 'foo bar hello world cya'
  23. ```


API


clsx(...input)

Returns: String

input

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!<br>Standalone Boolean values are discarded as well.


  1. ```js
  2. clsx(true, false, '', null, undefined, 0, NaN);
  3. //=> ''
  4. ```

Benchmarks


For snapshots of cross-browser results, check out the [bench](/bench) directory~!

Support


All versions of Node.js are supported.

All browsers that support [Array.isArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray#Browser_compatibility) are supported (IE9+).

>Note: For IE8 support and older, please install clsx@1.0.x and beware of #17.


Related


- obj-str - A smaller (96B) and similiar utility that only works with Objects.

License