Skip to content

Instantly share code, notes, and snippets.

@nestarz
Last active May 26, 2020 23:49
Show Gist options
  • Save nestarz/d24403c9350d68cb971142e2b4e41a51 to your computer and use it in GitHub Desktop.
Save nestarz/d24403c9350d68cb971142e2b4e41a51 to your computer and use it in GitHub Desktop.
Conditional Class using Object Representation
export const classs = (...args) =>
args
.flatMap((object) =>
object
? typeof object === "string"
? object
: Object.entries(object).reduce(
(str, [name, bool]) => (bool && name ? [...str, name] : str),
[]
)
: null
)
.filter((v) => v)
.join(" ");
// Use case
const active = false;
const className = classs("test", {active, important: true });
console.log(className) // Output: "test important"
const classs = (object) =>
Object.entries(object).reduce(
(str, [name, bool]) => `${str}${bool ? ` ${name}` : ""}`,
""
);
const className = classs({active: clicked, important: true });
console.log(className)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment