Skip to content

Instantly share code, notes, and snippets.

@EricMcWinNer
Created July 2, 2021 16:06
Show Gist options
  • Save EricMcWinNer/29a46ad741a1002432df2bf42f99ac2a to your computer and use it in GitHub Desktop.
Save EricMcWinNer/29a46ad741a1002432df2bf42f99ac2a to your computer and use it in GitHub Desktop.
My implementation of className, to allow more fluent class-binding in React
export const classBinding = obj => {
let classString = "";
if (Array.isArray(obj)) {
classString += obj.reduce((carry, item) => {
if ((typeof item === "string" || typeof item === "number") && item)
return `${carry}${carry ? " " : ""}${item}`;
else if (item) return `${carry}${carry ? " " : ""}${classBinding(item)}`;
else return carry + "";
}, "");
} else {
if (obj) {
if (typeof obj === "object") {
classString += Object.entries(obj)
.filter(entry => entry[1])
.reduce(
(carry, current) => carry + `${carry ? " " : ""}${current[0]}`,
""
);
} else if (typeof obj === "string") {
classString += obj;
} else classString += "";
} else {
classString += "";
}
}
return classString.trim();
};
export const classNames = (...args) => classBinding(args);
// classNames('test', 'name') => 'test name'
// classNames({test: true, name: false, new: true}) => 'test new'
// classNames(['test', 'name']) => 'test name'
// classNames('test', {name: true}, ['jinx', {clean: true}], undefined, null) => 'test name jinx clean'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment