Loop over the arguments. Skip anything falsy, add strings and numbers, flatten arrays recursively, and for objects add each key whose value is truthy. Join with spaces. That's the whole classnames contract: classNames('btn', { active: isActive }, [size &&btn-${size}]). Follow-ups interviewers like: a dedupe variant where a later { cls: false } removes an earlier class, binding to a CSS Modules styles object, objects that bring their own toString, and very deep arrays without recursion.
Implement classnames — combine class names from strings, arrays, and conditional objects.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Each argument type has one rule. Falsy values (false, null, undefined, 0, '') disappear, which is what makes cond && 'cls' work. Strings and numbers are added. Arrays recurse. An object contributes its own keys whose values are truthy. Duplicates are kept, as in the package.
// Strings and numbers are added, arrays are flattened, objects add their keys whose value is// truthy, and everything falsy (false, null, undefined, 0, '') is skipped.function classNames(...args) {const out = [];for (const arg of args) {if (!arg) continue;if (typeof arg === 'string' || typeof arg === 'number') out.push(arg);else if (Array.isArray(arg)) {const inner = classNames(...arg);if (inner) out.push(inner);} else if (typeof arg === 'object') {for (const key of Object.keys(arg)) if (arg[key]) out.push(key);}}return out.join(' ');}
passes 4 checks run on every build, against the native method where there is one
- strings, numbers and objects
- falsy values are skipped
- nested arrays flatten
- nothing gives an empty string
Keep a Map from class name to on/off. Strings are split on whitespace and switched on. Object keys are switched on or off by their value, so a later { primary: false } removes an earlier 'primary'. That's how a component can let callers override its default classes. A Map keeps first-seen order, so the output order is stable.
// The "dedupe" flavour: each class appears once, and a later false switches an earlier one// off, so defaults can be overridden: classNames('btn', props.className, { btn: !unstyled }).function classNames(...args) {const on = new Map(); // class -> included?; a Map keeps first-seen orderconst visit = (arg) => {if (!arg) return;if (typeof arg === 'string' || typeof arg === 'number') {for (const name of String(arg).split(/\s+/)) if (name) on.set(name, true);} else if (Array.isArray(arg)) {arg.forEach(visit);} else if (typeof arg === 'object') {for (const key of Object.keys(arg)) {for (const name of key.split(/\s+/)) if (name) on.set(name, Boolean(arg[key]));}}};args.forEach(visit);return [...on].filter(([, yes]) => yes).map(([name]) => name).join(' ');}
passes 4 checks run on every build, against the native method where there is one
- each class once
- a later false switches a class off
- switched back on keeps its first position
- extra spaces don't create empty classes
classNamesFor(styles) maps each class through a CSS Modules object (own properties only, so constructor isn't mistaken for a style). Objects with their own toString are used as strings, so a class-builder object can be passed straight in. A stack of iterators replaces recursion while keeping the order.
// Two extras from real use. CSS Modules: bind a styles object so 'button' becomes the hashed// class the build produced. And objects with their own toString (a class-name builder) are// asked for their string, as the classnames package does. No recursion, so any nesting works.function classNamesFor(styles = {}) {const map = (name) => (Object.prototype.hasOwnProperty.call(styles, name) ? styles[name] : name);return function classNames(...args) {const out = [];const stack = [args[Symbol.iterator]()];while (stack.length) {const step = stack[stack.length - 1].next();if (step.done) {stack.pop();continue;}const arg = step.value;if (!arg) continue;if (typeof arg === 'string' || typeof arg === 'number') out.push(map(String(arg)));else if (Array.isArray(arg)) stack.push(arg[Symbol.iterator]());else if (typeof arg === 'object') {const own = arg.toString;if (typeof own === 'function' && own !== Object.prototype.toString && !String(own).includes('[native code]')) {out.push(String(arg)); // its own toString: use it as is} else {for (const key of Object.keys(arg)) if (arg[key]) out.push(map(key));}}}return out.join(' ');};}const classNames = classNamesFor();
passes 5 checks run on every build, against the native method where there is one
- same results as the basic version on ordinary input
- bound to CSS Modules styles
- objects with their own toString
- deep nesting without recursion
- inherited style names aren't used
The classnames and clsx packages
classnames (and its smaller twin clsx) are among the most installed React utilities; both follow the rules in the basic stage.
CSS Modules
CSS Modules turn .button into a unique hashed class, so components look classes up through an imported styles object; classnames/bind does the mapping in the advanced stage.
Overriding default classes
Component libraries merge their default classes with className passed by the caller; the dedupe flavour lets a caller switch a default off.
Treating
0as a class: it's falsy and skipped (other numbers are kept).for...inwithout an own-property check, which picks up inherited keys.Leaving a trailing space or double spaces from skipped values (join only what's kept).
Expecting
{ a: false }to remove an earlier'a'in the basic version: only the dedupe flavour does that.
How does this differ from tailwind-merge?
classnames only joins strings; it doesn't know that p-2 and p-4 conflict. tailwind-merge parses Tailwind classes and keeps the last of each conflicting group.
Why accept numbers at all?
For generated class names such as grid columns; the package adds any non-zero number as a string.
How would you make it faster?
Build the string directly instead of an array, and avoid the object branch's key allocation; clsx does both, which is why it's smaller and quicker.