Sub topic 8
Conditional classes and component variants
This chapter shows how to switch CSS Module classes on and off from props. You will build a Button with a variant (primary or secondary) and a disabled state. It assumes you can already import a .module.css file and read styles.button. It also assumes you know basic React props and JSX, and how the cascade and specificity work in CSS.
Why conditional classes need a pattern
A component's appearance often depends on its props. A button can be primary or secondary, and it can be enabled or disabled. With CSS Modules, each of these looks is a class in the .module.css file. The component decides which classes to put on the element.
The styles object is a plain JavaScript object. Its keys are your local class names and its values are the generated, unique class names. That means you can pick a class by computing the key, and you can combine values with ordinary string logic.
The simplest approach is a template literal:
<button className={`${styles.button} ${styles[variant]}`}>This works until a value is undefined or false. Then the output contains the text undefined or false as a class name. The next sections avoid that problem.
Structure the CSS: base, variants, states
Split the styles into three kinds of classes:
- A base class holds what every instance shares, such as padding and border radius.
- Variant classes hold what differs between mutually exclusive looks, such as colors.
- State classes hold what is switched on or off independently, such as a disabled look.
.button {
padding: 0.5rem 1rem;
border: 0;
border-radius: 4px;
cursor: pointer;
}
.primary {
background: #2563eb;
color: #fff;
}
.secondary {
background: #e5e7eb;
color: #111827;
}
.disabled {
opacity: 0.5;
cursor: not-allowed;
}Each class has a single job. .primary and .secondary never appear together on one element. .disabled can appear with either of them.
Joining classes with clsx
The clsx package joins its arguments into one space-separated string and skips falsy values. Falsy values are false, undefined, null, 0 and the empty string. Install it with npm install clsx.
import clsx from 'clsx';
import styles from './Button.module.css';
export function Button({ variant = 'primary', disabled = false, children }) {
return (
<button
className={clsx(styles.button, styles[variant], disabled && styles.disabled)}
disabled={disabled}
>
{children}
</button>
);
}There are three arguments in this call:
styles.buttonis always present.styles[variant]looks up a class by name. Withvariant="secondary"it readsstyles.secondary.disabled && styles.disabledevaluates tofalsewhendisabledis false, soclsxdrops it. Whendisabledis true it evaluates to the generated class name.
For a primary, enabled button, the rendered element looks like this. The exact hashed names depend on your build configuration:
<button class="Button_button__x7Kq2 Button_primary__a91Zc">Save</button>With disabled set, the element gains a third class and the native disabled attribute. Set both. The class controls how the button looks. The attribute stops clicks and keyboard activation.
clsx also accepts objects, where each key is included if its value is truthy. Object keys are plain strings, so use computed keys with the styles values:
clsx(styles.button, {
[styles.disabled]: disabled,
[styles.loading]: isLoading,
});Use whichever form reads better. The condition && value form suits one or two flags. The object form suits several.
How the lookup flows
The diagram shows how props turn into the final className string.
Variant lookup and its failure modes
Looking up styles[variant] is compact, but it has two gotchas.
An unknown variant gives undefined. If a caller passes variant="danger" and there is no .danger class, styles.danger is undefined. clsx silently drops it, and the button renders with only the base class. No error appears. In plain JavaScript, this is easy to miss. In TypeScript, restrict the prop to a union type so the compiler catches it:
import clsx from 'clsx';
import styles from './Button.module.css';
type ButtonProps = {
variant?: 'primary' | 'secondary';
disabled?: boolean;
children: React.ReactNode;
};
export function Button({ variant = 'primary', disabled = false, children }: ButtonProps) {
return (
<button
className={clsx(styles.button, styles[variant], disabled && styles.disabled)}
disabled={disabled}
>
{children}
</button>
);
}The union type only protects the component's callers. It does not check that .primary and .secondary exist in the CSS file. If someone renames or deletes .secondary, the type still passes and the style quietly disappears. Typed CSS Module declarations, covered in a later chapter, can close that gap.
Dynamic lookup defeats tooling that looks for unused classes. A linter or a CSS-purging tool sees styles[variant] and cannot tell which classes are used. Some tools then keep every class, and others may flag them as unused. If that matters in your project, use an explicit map:
const variantClass = {
primary: styles.primary,
secondary: styles.secondary,
};
// inside the component
clsx(styles.button, variantClass[variant]);The map lists each class by its literal name, so static analysis can follow it. The cost is one more place to update when you add a variant.
Specificity and source order
All of these classes have the same specificity: one class selector each. When two of them set the same property on the same element, the later rule in the CSS file wins, not the class listed later in the className string.
In the example, .disabled sets opacity and cursor. .primary and .secondary do not set those properties, so there is no conflict. But suppose you add cursor: pointer to .primary. Because .disabled appears later in the file, cursor: not-allowed still wins, and the order of classes in the string is irrelevant.
Keep state classes after variant classes in the file. If you reverse them, a variant could override a state. When a state must beat a variant regardless of order, raise its specificity deliberately, for example with a compound selector:
.button.disabled {
opacity: 0.5;
cursor: not-allowed;
}Both classes in that selector are still locally scoped, so this stays inside the module.
Styling with state selectors instead of classes
Not every state needs a class. Native attributes and pseudo-classes already carry state, and CSS can target them directly:
.button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.button[aria-pressed='true'] {
outline: 2px solid #2563eb;
}With this approach, the component only sets disabled and aria-pressed. It does not need to compute a class for them. This keeps one source of truth, because the class and the attribute cannot disagree. Use a class when no native attribute describes the state, such as loading or highlighted.
Data attributes as an alternative
A data-* attribute can carry a variant name, with the styling in attribute selectors:
.button[data-variant='primary'] {
background: #2563eb;
color: #fff;
}
.button[data-variant='secondary'] {
background: #e5e7eb;
color: #111827;
}<button className={styles.button} data-variant={variant}>| Approach | Strength | Weakness |
|---|---|---|
| Variant classes with `clsx` | Familiar, works with `composes`, easy to grep | Dynamic lookup can hide unused classes |
| Native state selectors (`:disabled`) | No extra code, cannot drift from behavior | Only covers states the browser knows |
| `data-` attributes | One attribute holds the variant, DOM shows state clearly | Attribute values are plain strings, not scoped or checked |
Attribute values are not renamed by the build, so data-variant="primary" appears literally in the DOM. That is fine for styling, but it also means tests and external code can depend on it.
Common mistakes
- Template literals with falsy values. `
${styles.button} ${disabled && styles.disabled}outputsfalseas a class whendisabledis false. Useclsx`. - Quoted class names.
className="button"does not use the module. It adds the literal classbutton, which no scoped rule matches. WriteclassName={styles.button}. - Combining two variants. Passing both
.primaryand.secondarymakes the winner depend on file order. Model variants as one prop with one value. - Forgetting the native attribute. A
.disabledclass alone makes a button look disabled but still clickable.
Exercise
Exercise
A Button is rendered with variant="ghost", but Button.module.css has no .ghost class. The component uses clsx(styles.button, styles[variant]). What class names does the element get, does React or the bundler report an error, and how can you catch the mistake earlier?
Show answer
The element gets only the generated button class, because styles.ghost is undefined and clsx drops it. No error is reported. To catch it earlier, type the variant prop as a union such as 'primary' | 'secondary' so TypeScript rejects "ghost", or add the .ghost class. Typed CSS Module declarations can also flag a missing class.
Exercise
You add cursor: pointer to .primary, and .disabled (which sets cursor: not-allowed) appears earlier in the CSS file than .primary. A disabled primary button shows a pointer cursor. Why, and what are two ways to fix it?
Show answer
Both selectors have the same specificity, so the rule later in the file wins, and that is .primary. Fix it by moving .disabled after .primary in the file, or by raising specificity with a compound selector such as .button.disabled. Using .button:disabled also works because a pseudo-class adds specificity.