Skip to content

Instantly share code, notes, and snippets.

@Fredkiss3
Last active January 3, 2023 14:54
Show Gist options
  • Save Fredkiss3/9472d0cce73ef4e80462d7a560319771 to your computer and use it in GitHub Desktop.
Save Fredkiss3/9472d0cce73ef4e80462d7a560319771 to your computer and use it in GitHub Desktop.
A custom utility for classnames
/**
* Concatenate the specified classNames automatically with spaces.
* - If the className is undefined, it is ignored.
* - If the className is passed as a record of {class: condition }, it returns the class only if the condition is true.
*
* @example
* clsx('class1', 'class2', { class: true }) // 'class1 class2 class'
* clsx('class1', 'class2', { class: false }) // 'class1 class2'
* clsx('class1', undefined) // 'class1'
*
* @param args
* @returns
*/
export function clsx(
...args: (string | undefined | Record<string, boolean>)[]
): string {
const classes: string[] = [];
for (const arg of args) {
switch (typeof arg) {
case 'string':
classes.push(arg);
break;
case 'object':
for (const key in arg) {
if (arg[key]) {
classes.push(key);
}
}
break;
}
}
return classes.join(' ');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment