Sub topic 7
Combining several classes on one element
This chapter assumes you can write React function components and JSX. It also assumes you know how to import a .module.css file and read from the styles object. Both were covered earlier in this tutorial. Here the question is what to do when one element needs more than one class.
Why one element needs several classes
A real button has a base look, a variant such as primary or secondary, and sometimes a state such as disabled. If you write each of these as its own class, the CSS stays small and each rule does one job. The component then has to put those classes on the element together.
.button {
padding: 0.5rem 1rem;
border: 0;
border-radius: 4px;
cursor: pointer;
}
.primary {
background: #2563eb;
color: #fff;
}
.large {
padding: 0.75rem 1.5rem;
font-size: 1.125rem;
}The HTML class attribute takes a space-separated list of names. In React, className is a single string, so combining classes means building a string. The values on styles are already strings, so this is plain string work.
What the styles object gives you
Each key on the imported object is a string holding the generated class name. A key that does not exist in the CSS file gives undefined. That difference matters for every technique below.
import styles from './Button.module.css';
console.log(styles.button); // for example "Button_button__x7Qa2"
console.log(styles.missing); // undefinedThe exact generated name depends on your bundler configuration. Do not depend on its shape.
flowchart TDThe diagram below shows the path from several lookups to one className value.
Technique 1: template literals
The simplest way to combine two classes is a template literal.
import styles from './Button.module.css';
export function Button({ children }) {
return (
<button className={`${styles.button} ${styles.primary}`}>
{children}
</button>
);
}This works when every class is always present. It breaks down as soon as one part might be missing.
// Bug: if size is undefined, styles[size] is undefined
const className = `${styles.button} ${styles[size]}`;
// The class attribute becomes "Button_button__x7Qa2 undefined"JavaScript converts undefined to the text "undefined". The element gets a class literally named undefined. Nothing crashes, and no style is applied, so the bug is easy to miss.
Technique 2: arrays, filter and join
You can collect the classes in an array, remove falsy entries, and join the rest.
import styles from './Button.module.css';
export function Button({ size, children }) {
const className = [styles.button, styles.primary, size && styles[size]]
.filter(Boolean)
.join(' ');
return <button className={className}>{children}</button>;
}filter(Boolean) removes undefined, false, null, 0 and the empty string. When size is undefined, the expression size && styles[size] evaluates to undefined and is dropped. When size is "large", it evaluates to the generated name for .large.
This needs no dependency, but you repeat the pattern in every component. Many teams wrap it in a tiny helper or use a library.
Technique 3: clsx or classnames
clsx and classnames are small libraries that do the filter-and-join work for you. Their call syntax is nearly the same. This chapter uses clsx, which you install with npm install clsx.
import clsx from 'clsx';
import styles from './Button.module.css';
export function Button({ size, disabled = false, children }) {
return (
<button
className={clsx(
styles.button,
styles.primary,
size && styles[size],
disabled && styles.disabled
)}
disabled={disabled}
>
{children}
</button>
);
}clsx accepts several argument types and flattens them.
| Argument | Example | Result |
|---|---|---|
| String | `clsx(styles.a, styles.b)` | Both names, space separated |
| Falsy value | `clsx(styles.a, false, undefined, null)` | Only `styles.a` |
| Object | `clsx({ [styles.on]: isOn })` | `styles.on` only when `isOn` is truthy |
| Array | `clsx([styles.a, cond && styles.b])` | Flattened, falsy values dropped |
Object syntax and computed keys
The object form uses class names as keys. With CSS Modules, the key is the generated name, so you must write it as a computed key in square brackets.
import clsx from 'clsx';
import styles from './Card.module.css';
export function Card({ selected, compact, children }) {
const className = clsx(styles.card, {
[styles.selected]: selected,
[styles.compact]: compact,
});
return <div className={className}>{children}</div>;
}A common mistake is to write { styles.selected: selected }, which is a syntax error. Another is to write { selected: selected }. That is valid JavaScript, but it adds the plain name selected, which has no CSS rule attached. The element renders unstyled and no error appears.
The classnames/bind alternative
The classnames package also offers a bind variant. It looks up each name on the styles object for you, so you can use the local names directly.
import classNames from 'classnames/bind';
import styles from './Card.module.css';
const cx = classNames.bind(styles);
export function Card({ selected, children }) {
return <div className={cx('card', { selected })}>{children}</div>;
}This is shorter, but names are now strings. A typo such as cx('crad') silently produces no class, and editors cannot rename them with the CSS file. Choose one style per project.
Accepting a className prop from a parent
A reusable component often lets the caller add its own class, for example to adjust margins. Combine the incoming prop with your own classes.
import clsx from 'clsx';
import styles from './Badge.module.css';
export function Badge({ className, children }) {
return <span className={clsx(styles.badge, className)}>{children}</span>;
}The parent imports its own module and passes its own generated class.
import { Badge } from './Badge';
import styles from './Header.module.css';
export function Header() {
return <Badge className={styles.headerBadge}>New</Badge>;
}Both classes are on the element. Which declaration wins when both set the same property depends on specificity first. When specificity is equal, the rule that appears later in the final stylesheet wins. The order of the class names in the class attribute does not matter. Bundlers decide stylesheet order from import order, which can change as your app grows. If a parent override must win, do not rely on import order. Raise specificity on purpose, for example with .headerBadge.headerBadge, or avoid setting the same property in both files.
Edge cases
- Order inside
classNamehas no effect."a b"and"b a"behave identically. Only the CSS source order and specificity matter. - Duplicates are harmless but wasteful. Passing the same class twice produces it twice in the string. Browsers ignore the repeat.
- Dynamic lookups hide typos.
styles[variant]returnsundefinedfor a name that is not in the CSS file.clsxdrops it silently. Restrictvariantwith TypeScript or a default value so mistakes are visible. - A class used only through a dynamic key can be missed by tooling. Linters that detect unused CSS classes may not see
styles[variant]as a use of.secondary. - Names with hyphens need bracket access.
styles['primary-large']works, whilestyles.primary-largeis parsed as a subtraction. The next chapters cover naming in detail.
Choosing a technique
| Situation | Use |
|---|---|
| Two or three classes, always present | Template literal |
| A few conditions, no dependency wanted | Array with `filter(Boolean).join(' ')` |
| Many conditions or a `className` prop | `clsx` |
| Existing codebase already uses `classnames/bind` | Keep `cx` and stay consistent |
Exercise
A component renders <div className={${styles.card} ${styles[tone]}}>. When tone is not passed, the element still gets a class attribute that ends with the word "undefined". Rewrite the className expression with clsx so that no extra word appears, and add a selected class from styles.selected only when a boolean selected prop is true.
Show answer
Use className={clsx(styles.card, tone && styles[tone], selected && styles.selected)}. When tone is undefined, tone && styles[tone] evaluates to undefined and clsx drops it. When selected is false, selected && styles.selected evaluates to false and is also dropped. The object form clsx(styles.card, { [styles.selected]: selected }) is equivalent for the second part.
Exercise
A teammate writes clsx(styles.item, { active: isActive }) and the active style never applies, although .active exists in Item.module.css. What is wrong and how do you fix it?
Show answer
The key active is the plain string "active", not the generated class name, so the element gets a class with no matching rule. Use a computed key: clsx(styles.item, { [styles.active]: isActive }).