Skip to content
Build a space-separated class attribute quickly.
JavaScript TypeScript
Branch: master
Clone or download
Latest commit f40e544 Jul 8, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
bench Change titles Jun 27, 2019
src Cut a few bytes Jun 28, 2019
test test: so we can import by name in ts test Sep 3, 2018
.gitignore git: better .gitinore; ignore coverage output Aug 17, 2018
.travis.yml ci: refactor node ver order Aug 17, 2018
LICENSE.md JorgeBucaran→jorgebucaran & KB→kB Feb 27, 2018
README.md Less meta Jul 8, 2019
classcat.d.ts Remove confusing description Jun 27, 2019
package.json 4.0.2 Jun 29, 2019

README.md

Classcat npm

Build a space-separated class attribute quickly.

  • Easily add and remove class names based on a truthy or falsy value.
  • Works with any view framework—React, Preact, Hyperapp—your pick!
  • Up to 5x faster than the alternatives (run the benchmarks).
  • Tiny (260B) and no dependencies.

Quickstart

npm i classcat

Don't want to set up a build step? Import Classcat in a <script> tag as a module. Don't worry; modules are supported in all evergreen, self-updating desktop, and mobile browsers.

<script type="module">
  import cc from "https://unpkg.com/classcat"
</script>

Here's the first example to get you started: a toggle button.

import cc from "classcat"

export const ToggleButton = ({ isOn }) => (
  <div class="btn">
    <div
      class={cc({
        circle: true,
        off: !isOn,
        on: isOn
      })}
    />
    <span class={cc({ textOff: !isOn })}>{isOn ? "ON" : "OFF"}</span>
  </div>
)

The cc function takes a list of class names as an array or object of name-value pairs and joins all the truthy values into a space-separated string. Arrays can also contain objects and even nested arrays. That's really all there is to it!

API

cc(string | number | object | array)

import cc from "classcat"

cc("foo") //=> "foo"

cc(["foo", "bar", "baz"]) //=> "foo bar baz"

cc({ foo: false, bar: null, baz: undefined }) //=> ""

cc({ foo: true, bar: false, baz: true }) //=> "foo baz"

cc([{ foo: true, bar: false }, "baz"]) //=> "foo baz"

Run the benchmarks

npm run build && npm i -C bench && npm -C bench start
# Strings
classcat × 20,689,684 ops/sec
classnames × 4,189,458 ops/sec

# Objects
classcat × 25,207,387 ops/sec
classnames × 4,479,830 ops/sec

# Strings/Objects
classcat × 15,050,993 ops/sec
classnames × 3,731,854 ops/sec

# Arrays
classcat × 5,333,405 ops/sec
classnames × 1,120,879 ops/sec

# Arrays/Objects
classcat × 6,907,586 ops/sec
classnames × 2,786,756 ops/sec

License

MIT

You can’t perform that action at this time.