Sub topic 8
Conditional classes and component variants
This chapter assumes you can write React components with props and JSX. It also assumes you have already imported a .module.css file and applied a class through the styles object. Here you will switch classes based on props to build component variants.
The idea: base, variant and state classes
A component such as a button usually has three kinds of styling:
- A base class with styles every button shares, such as padding and border radius.
- A variant class that picks a look, such as primary or secondary.
- A state class that applies only in some situations, such as disabled.
Keeping these in separate classes lets you combine them from the component instead of repeating declarations.
.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;
}Joining classes with clsx
The className prop takes one string. To apply several classes, you need to join them. The clsx package does this and skips falsy values such as false, undefined and null. 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>
);
}Each argument does a different job:
styles.buttonis always applied.styles[variant]uses bracket access to look up a class by the value of thevariantprop. Withvariant="secondary", it resolves tostyles.secondary.disabled && styles.disabledevaluates tofalsewhendisabledis false, andclsxdrops it.
With the default props, the rendered element gets two generated class names, for example Button_button__x1y2z Button_primary__a3b4c. The exact names depend on your build tool.
Why not template strings?
You could write ` ${styles.button} ${styles[variant]} . This works until a value is undefined, when the string contains the text undefined as a class name. clsx` avoids this by ignoring falsy values.
Common errors
- An unknown variant gives no styles. If a caller passes
variant="danger"and the CSS file has no.dangerclass,styles.dangerisundefined. React renders no error andclsxskips it. The button just looks unstyled. In TypeScript, restrict the prop to a union such as'primary' | 'secondary'. - Class names that need quotes. A class named
.is-activecannot be read asstyles.isActive. Usestyles['is-active'], or name the class in camelCase. - Disabled look without disabled behavior. The
disabledclass only changes appearance. Also pass thedisabledattribute to the element, as the example does. - Specificity surprises. If
.disabledsetsbackgroundand.primaryalso sets it, the rule that appears later in the CSS file wins, not the one listed later inclsx. Order matters in the stylesheet.
Exercise
A caller renders <Button variant="secondary" disabled /> using the component above. Which classes does the button receive, and what happens if .secondary and .disabled both set opacity or background and .secondary is defined later in the CSS file?
Show answer
It receives the generated names for button, secondary and disabled. For any property set in both .secondary and .disabled, the declaration that appears later in the CSS file wins. Because .secondary is defined later, its value overrides .disabled. The order in the clsx call does not change this. To fix it, move .disabled below the variant classes.
Exercise
Why is styles[variant] preferred over a chain of variant === 'primary' && styles.primary checks?
Show answer
Bracket access looks up the class by name in one expression, so adding a new variant needs only a new CSS class and no new code in the component. The chain must be extended for every variant.