Sub topic 4
Applying classes through the styles object
This chapter assumes you can write React function components with props and JSX, and that your project already builds .module.css files (Vite, webpack, or Next.js all do this by default). It covers the import itself and the object it gives you. Later chapters cover combining classes, variants, and composes in detail.
What the import gives you
A CSS Modules file is plain CSS with a special file name: it ends in .module.css. When you import it, the bundler processes the CSS and hands your JavaScript an object. That object is conventionally named styles.
Start with a stylesheet:
.button {
padding: 0.5rem 1rem;
border: 0;
border-radius: 4px;
background: #2563eb;
color: #fff;
cursor: pointer;
}
.button:hover {
background: #1d4ed8;
}Now import it from a component:
import styles from './Button.module.css';
export function Button({ children }) {
return <button className={styles.button}>{children}</button>;
}The default import styles maps each local class name in the file to a generated, unique class name. For this file, styles looks roughly like this at runtime:
{ button: "Button_button__3kF9a" }The exact string depends on your tooling and configuration. Treat it as opaque. The className prop receives that string, so the browser sees class="Button_button__3kF9a", and the generated CSS rule uses the same name.
From file to DOM
Both sides of the connection are rewritten with the same generated name. That is why a plain .button in two different files does not collide.
The component never sees the original .button text. It only sees the lookup table. This is the central idea of the chapter: you refer to a class by its key in styles, never by its literal name.
Why a string does not work
A common first mistake is to write the class name as a string:
// Wrong: "button" is not the generated name, so no CSS rule matches.
<button className="button">Save</button>This renders class="button". The stylesheet no longer contains a rule for .button, because the bundler renamed it. The element silently gets no styles. There is no error, which makes this bug easy to miss.
Always read the name from the object:
<button className={styles.button}>Save</button>Local names inside the CSS file
Inside a .module.css file, you write class names normally in every selector. Each class you write is rewritten, including those in compound selectors, pseudo-classes, and media queries.
.card {
border: 1px solid #d1d5db;
}
.card.selected {
border-color: #2563eb;
}
@media (min-width: 40rem) {
.card {
display: flex;
}
}The styles object now has two keys, card and selected. The .card.selected selector means "an element that has both generated classes." You would apply both from the component. A single key is not enough, because styles.selected alone would not satisfy the compound selector.
Every class name that appears anywhere in the file becomes a key, whether or not the component uses it. A key exists even if it appears only inside another selector.
Reading keys: dot and bracket access
Class names that are valid JavaScript identifiers can use dot access: styles.button. Names with hyphens cannot, so use bracket access: styles['primary-button']. Many teams avoid the issue by writing class names in camelCase (primaryButton) so that dot access always works. The next chapter in the plan treats naming conventions in detail. Some bundlers can also convert hyphenated names to camelCase keys for you, but this is a configuration option and not the default everywhere. Check yours before relying on it.
You can also look up a key from a variable, which is useful when a prop selects the class:
import styles from './Alert.module.css';
export function Alert({ tone = 'info', children }) {
return <div className={styles[tone]}>{children}</div>;
}.info {
background: #dbeafe;
}
.error {
background: #fee2e2;
}If tone is "warning" and the CSS has no .warning class, styles[tone] is undefined. React omits the class attribute when className is undefined, so the element renders with no styles and no error. Pass only values you have defined, or give the lookup a fallback:
<div className={styles[tone] ?? styles.info}>{children}</div>Applying more than one class
An element often needs a base class plus an extra one. The simplest approach is a template literal:
<button className={`${styles.button} ${styles.primary}`}>Save</button>This works but becomes awkward once any class is conditional, because a missing class becomes the text undefined inside the string. Small helpers such as clsx solve that, and a later chapter covers them. For now, remember the rule: className takes one string, so build one string.
Element selectors and what they do not do
CSS Modules only rewrites class names (and ID names, and a few other identifiers such as keyframes). A selector like this is not scoped:
h2 {
margin: 0;
}It applies to every h2 on the page, in every component. Scoping comes from the class, so give the element a class and select by it:
.title {
margin: 0;
}<h2 className={styles.title}>Profile</h2>A selector such as .card h2 is partly scoped. .card is local, so it only matches inside that component's card. The h2 part still matches any h2 descendant, including ones rendered by child components. That can cause surprises, so prefer classes for anything you style.
Reading the object during development
When styling does not appear, inspect the object directly:
import styles from './Button.module.css';
console.log(styles);This prints the key-to-name mapping. Check three things:
- The key you read exists in the object.
- The class is spelled the same way in the CSS file and in your code.
- The rendered element in the browser inspector has the generated class, and the rule shows under it.
An empty object usually means the file was not treated as a CSS Module. Confirm the file name ends in .module.css. A file named Button.css is imported as ordinary global CSS and yields no useful default export.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Element has `class="button"` and no styles | Wrote a string instead of `styles.button` | Use `styles.button` |
| No `class` attribute at all | Key is missing, so the value is `undefined` | Check spelling; add the class or a fallback |
| `styles` is `{}` or has no default export | File is not named `*.module.css` | Rename the file |
| `styles.primary-button` is a syntax error | Hyphen parsed as subtraction | Use `styles['primary-button']` or camelCase |
| Text `undefined` in the class list | Template literal with a missing key | Use a helper that skips falsy values |
| Rule from one component leaks to others | Element selector without a class | Select with a class |
Exercise
Exercise
A teammate writes <div className="card"> in Card.jsx, with .card { border: 1px solid #ccc; } defined in Card.module.css, and reports that the border never appears. Name the cause and give the corrected line. Then explain what styles['card-header'] would return if the CSS file defined only .cardHeader.
Show answer
The CSS Modules build renamed .card to a generated name such as Card_card__x9a2b, so the literal string "card" matches no rule. Import the object with import styles from './Card.module.css'; and write <div className={styles.card}>. For the second part, styles['card-header'] returns undefined, because the key is cardHeader. React omits the class attribute for an undefined className, so the element gets no styles and no error is thrown.