Skip to content

A utility to keep your CSS classes in JS consistently and semantically grouped

License

Notifications You must be signed in to change notification settings

itech-media/classgroup

Repository files navigation

ClassGroup

ClassGroup is a utility to help keep your CSS classes in JS consistently and semantically grouped while allowing for a separation of concerns.

It helps unclutter your markup when using utility-driven CSS principles or frameworks such as TailwindCSS with negligible performance impact. It improves readability of components, improving Developer Experience.

Installation

npm i -D classgroup

Usage

To use ClassGroup, import it as you would any other utility:

import ClassGroup from 'classgroup';

If your project uses CommonJS, then:

import ClassGroup from 'classgroup/commonjs';

We then use this simple function by passing in an object with our groupings.

const classes = ClassGroup({
  identifier: value,
});

The key is an identifier and is just for our own reference - think of it like the class names you would give when writing traditional CSS.

The value can be a string, array or object with no limit on nesting depth so you can group in anyway you like.

It will return a flattened object that for convention we store in a variable called classes. You can then access the resultant string referencing by dot notation

// Svelte, Vue
<div class="{classes.identifier}">...</div>

// React
render() {
  return <div className={classes.identifier}>...</div>
}

ClassGroup is written in Typescript and uses the following types internally:

// ClassGroup.d.ts

export interface Output {
  [key: string]: string;
}

export type OptionValue = boolean | string | Array<string> | Options;

export interface Options {
  [key: string]: OptionValue;
}

export default function ClassGroup(collection: Options, ...overrides: Options[]): Output;

Let's take a look at a few examples so that this makes sense and see how we can apply this.

Basic Abstraction with Strings or Arrays

const classes = ClassGroup({
  container: 'class1 class2',
  btn: ['class3', 'class4'],
});

console.log(classes);

// Results in:
// {
//   container: "class1 class2",