Created
July 2, 2021 16:06
-
-
Save EricMcWinNer/29a46ad741a1002432df2bf42f99ac2a to your computer and use it in GitHub Desktop.
My implementation of className, to allow more fluent class-binding in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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