Skip to content

Instantly share code, notes, and snippets.

@jasonsperske
Created April 2, 2025 00:01
Show Gist options
  • Save jasonsperske/af62638eb1306daf3c5d1253077decfa to your computer and use it in GitHub Desktop.
Save jasonsperske/af62638eb1306daf3c5d1253077decfa to your computer and use it in GitHub Desktop.
className helper
/**
* Function that takes any number of strings or records of booleans or functions that return booleans
* and returns a string of class names that are true.
* @param classes
* @returns
*/
export function cn(...classes) {
return classes
.flatMap(c =>
typeof c === 'string'
? c
: Object.entries(c)
.filter(([, v]) => (typeof v === 'function' ? v() : v))
.map(([k]) => k)
)
.join(' ')
}
/**
* Function that takes any number of strings or records of booleans or functions that return booleans
* and returns a string of class names that are true.
* @param classes
* @returns
*/
export function cn(...classes: Array<string | Record<string, boolean | (() => boolean)>>): string {
return classes
.flatMap(c =>
typeof c === 'string'
? c
: Object.entries(c)
.filter(([, v]) => (typeof v === 'function' ? v() : v))
.map(([k]) => k)
)
.join(' ')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment