Write classNames(...args). It builds a class attribute value from any mix of arguments and returns the class names joined with single spaces, in the order they appear.
A non-empty string, or a number other than 0, is added as it is. An object adds each of its own enumerable keys whose value is truthy, in key order. An array is handled as if its items had been passed as arguments, at any depth. Everything else is skipped: false, null, undefined, 0, NaN, "", and true.
The result never has leading, trailing, or double spaces, and with nothing to add it's "". Duplicates are kept.
classNames("btn", { active: true, disabled: false }, ["lg", null]);
// "btn active lg"
classNames("card", isOpen && "open");
// "card open", or "card" when isOpen is false
expect(classNames("btn", "primary")).toBe("btn primary");
expect(classNames("one")).toBe("one");
expect(classNames({ active: true, disabled: false, open: 1, hidden: null, "is-new": "yes" })).toBe("active open is-new");
expect(classNames(["a", ["b", [{ c: true, x: false }]]], "d")).toBe("a b c d");
expect(classNames(null, "a", false, undefined, 0, "", true, NaN, "b")).toBe("a b");
expect(classNames("col", 12, 0)).toBe("col 12");
expect(classNames({ b: true }, "a", { d: true, c: true })).toBe("b a d c");
expect(classNames()).toBe("");
expect(classNames(false, "a", null)).toBe("a");
expect(classNames("", [], {}, "b", [null, false])).toBe("b");
expect(classNames([null, false], { off: false })).toBe("");
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with classNames. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.