Skip to content

Instantly share code, notes, and snippets.

@joe-bell
Last active October 19, 2020 10:26
Show Gist options
  • Save joe-bell/2a77015a4f799d67e47a6ab812ccd6c2 to your computer and use it in GitHub Desktop.
Save joe-bell/2a77015a4f799d67e47a6ab812ccd6c2 to your computer and use it in GitHub Desktop.
Tailwind Classnames
const heading = ["font-inter", "font-bold"];
const config = {
// Components
"c.heading": heading,
"c.h1": [...heading, "text-5xl"],
"c.h2": [...heading, "text-4xl"],
"c.h3": [...heading, "text-3xl"],
"c.container": ["block", "mx-auto", "max-w-5xl", "px-4"],
// Utilities
"u.border": ["border-line", "border-4"],
};
/**
* Classnames
*
* Concatenate classes (including pre-defined class arrays)
*/
export const cx = (...classNames: (keyof typeof config | ({} & string))[]) =>
classNames
.map((className) =>
config.hasOwnProperty(className) ? config[className] : className
)
.flat()
.filter(Boolean)
.join(" ");
// Autocompletes config keys (+ works with Tailwind IntelliSense)
export const Example = () => (
<h1 className={cx("c.h1", "mt-4", "some-other-class")}>Heading 1</h1>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment