/classcat

0.3 KB JavaScript function for conditionally concatenating CSS class names.

Primary LanguageJavaScriptMIT LicenseMIT

Classcat

Travis CI Codecov npm

Classcat is a 0.3 KB JavaScript function for conditionally concatenating CSS class names.

Live Example

import cc from "classcat"

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

Classcat works in all browsers >= IE9 and you can use it with your favorite JavaScript UI library.

Classcat

Installation

Install with npm / Yarn.

npm i classcat

Then with a module bundler like Rollup or Webpack, use as you would anything else.

import cc from "classcat"

If you prefer not to use a build system, you can load Classcat from a CDN and it will be globally available through the window.classcat object.

<!doctype html>
<html>
<body>
  <script src="https://unpkg.com/classcat"></script>
  <script>

  const cc = classcat

  </script>
</body>
</html>

Usage

Classcat is a unary function (accepts a single argument) expecting an array of elements or an object of keys and returns a string that is the result of joining all elements of the array or object keys.

If the value associated with a given key is falsey, the key will be ignored.

cc([
  "btn",
  {
    "btn-active": true,
    "btn-large": false
  }
]) // => btn btn-active

If an object contains child elements, the parent key will be used as a prefix.

cc([
  "tab",
  {
    tab: {
      "--success": true,
      "--error": false,
      "--pending": false
    }
  }
]) // => tab tab--success

Credits

Classcat is inspired by JedWatson/classNames with support for nested objects and better performance. The difference between classcat and classNames is that classNames accepts a variable number of arguments, whereas classcat only accepts a single argument.

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

To work around this, wrap the arguments inside an array.

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

License

Classcat is MIT licensed. See LICENSE.