className helper
npm install class-cclass-c> Chainable class name helper with first class CSS Module support
- class-c
- Installation
- Usage
- Basic
- Function values
- Chaining
- Conditionals
- CSS Modules
- Chaining
- Many references
- Multiple modules/styles objects
- Prefixing and suffixing
``bash`
$ npm install class-c
c uses the tagged template syntax
`ts
import c from "class-c";
ca b; // => "a b"
// Extra whitespace will be removed
c a b ; // => "a b"
c
a
b; // => "a b"
// Calling with a string can be useful for class forwarding, see CSS Modules section
c("a b"); // => "a b"
`
Functions passed into the template will be unwrapped to their return value
`ts
import c from "class-c";
ca ${() => "b"}; // => "a b"`
You can chain as many scopes as you'd like
`tsa
c.cb c.cd; // => "a b c d"
// This is more useful when used with CSS Modules, see CSS Modules section for more details
const styles = {
a: "scoped-a",
b: "scoped-b",
};
c(styles)a b.ca b; // => "scoped-a scoped-b a b"`
Falsey values will be omitted, condition-by-class mapping is also supported. This can be useful with object shorthand. This also supports function conditions.
`tsa ${condition && b}
c; // => condition ? "a b" : "a"
ca ${{ b: false, c: true }}; // => "a c"
const focused = true;
const highlighted = false;
const open = true;
c${{ focused, highlighted, open }}; // => "focused open"
// Function conditions
const focused = () => true;
const highlighted = () => false;
const open = () => true;
c${{ focused, highlighted, open }}; // => "focused open"
// Function values may also return conditional maps
c${() => ({ focused, highlighted, open })}; // => "focused open"`
Calling c with a styles object will create a scoped context
`ts
const styles = {
a: "scoped-a",
b: "scoped-b",
};
c(styles)a b; // => "scoped-a scoped-b"`
#### Chaining
Chaining will reset context which can be useful for forwarding classes
`tsa b
c(styles).ca b; // => "scoped-a scoped-b a b"
// Forwarding classes
const someExternalClasses = "external-a external-b";
c(styles)a b.c(someExternalClasses); // => "scoped-a scoped-b external-a external-b"`
#### Many references
If you need to use a context in many places, it can be convenient to make a new helper
`ts
const cs = c(styles);
csa; // => "scoped-a"
// Chaining will still reset context
csb.cc; // => "scoped-b"`
#### Multiple modules/styles objects
`ts
const otherStyles = {
a: "other-a",
b: "other-b",
};
c(styles)a b.c(otherStyles)a b; // => "scoped-a scoped-b other-a other-b"`
`tsa nonexistant b
// Non existant classes will be removed
c(styles); // => "scoped-a scoped-b"`
#### Prefixing and suffixing
`ts
const styles = {
variant_a: "scoped-variant_a",
variant_b: "scoped-variant_b",
};
const variant: "a" | "b" = "a";
c(styles)variant_${variant}; // => "scoped-variant_a"
const suffixStyles = {
a_suffix: "scoped-a_suffix",
b_suffix: "scoped-b_suffix",
};
c(suffixStyles)${variant}_suffix; // => "scoped-variant_a"``