Classcat is a declarative string builder for DOM className properties.
Each class can be conditionally added and removed depending on the falsiness of the value it is paired with. Here is a button you can toggle on and off. Go ahead and try it online.
import cc from "classcat"const ToggleButton = isOn<div ="btn"><div=/><span =>isOn ? "ON" : "OFF"</span></div>
- Tiny (294B)
- Zero dependency
- 5x faster drop-in replacement for JedWatson/classNames
- Framework agnostic—use with React, Preact, Hyperapp, your choice!
npm i classcat
Don't want to set up a build environment? Download classcat from a CDN and it will be globally available through the
window.classcat object. Classcat works in all browsers >= IE9.
Classcat expects an array of elements or an object of key/value pairs and joins all the elements in the array and object keys. Falsy array elements and object properties will be ignored. Single string or number values need not be in an array.
import cc from "classcat"//=> "foo"//=> "foo"//=> "foo baz"//=> "foo baz"
Arrays will be recursively flattened as per the rules above.
//=> "foo bar baz"
Variable number of arguments are not supported. Wrap multiple arguments in an array.
Use to set the class/className of an element created with your chosen view framework.
const popupView =<div=>popupcontent</div>
A number, string, object or array. Objects consist of className/value pairs. Arrays are recursively reduced, therefore elements can be of any type aforementioned. Truthy values are added to the output, falsy values are ignored.
//=> "foo bar baz"
All benchmarks run on a 2.4GHz Intel Core i7 CPU with 16 GB memory.
npm run build && npm i -C bench && npm -C bench start
# Strings classnames × 3,187,131 ops/sec classcat × 15,132,350 ops/sec # Objects classnames × 3,314,869 ops/sec classcat × 20,206,909 ops/sec # Strings & Objects classnames × 2,937,509 ops/sec classcat × 11,734,207 ops/sec # Arrays classnames × 903,155 ops/sec classcat × 4,270,378 ops/sec # Arrays & Objects classnames × 2,342,018 ops/sec classcat × 5,083,398 ops/sec
Classcat is MIT licensed. See LICENSE.