Sub topic 6
Naming classes: camelCase and bracket access
This chapter covers how the class names you write in a .module.css file become keys on the styles object. It also covers how to read those keys from JSX. It assumes you can already create and import a .module.css file and apply a class with styles.something. It also assumes you know the JavaScript difference between dot access and bracket access on an object.
The styles object is a plain JavaScript object
When you write import styles from './Card.module.css', the bundler gives you an object. Each local class name in the CSS file is a key. Each value is the generated, unique class name for that class, which the bundler produces at build time.
.card {
padding: 1rem;
}
.cardTitle {
font-weight: 600;
}
.card-footer {
color: #6b7280;
}For this file, styles looks roughly like this. The exact generated strings depend on your tooling.
const styles = {
card: 'Card_card__x7Kq2',
cardTitle: 'Card_cardTitle__a91Zp',
'card-footer': 'Card_card-footer__m3Lw8',
};Because styles is an ordinary object, the usual JavaScript rules for property names apply. That is why the choice between .cardTitle and .card-footer matters.
Why the naming style matters
Dot access, as in styles.cardTitle, only works when the key is a valid JavaScript identifier. A name with a hyphen is not one. styles.card-footer is parsed as styles.card - footer, a subtraction. At best this gives NaN or a ReferenceError for footer. It never reads the class.
You have two ways to deal with hyphenated names:
- Write class names in camelCase in the CSS file, so dot access works everywhere.
- Keep kebab-case in the CSS and use bracket access in JavaScript.
import styles from './Card.module.css';
export function Card({ title, children }) {
return (
<section className={styles.card}>
<h2 className={styles.cardTitle}>{title}</h2>
{children}
<footer className={styles['card-footer']}>Updated today</footer>
</section>
);
}Both styles work. Mixing them in one project makes code harder to scan, so choose one as a team convention.
Option 1: camelCase in the CSS file
Writing .cardTitle in CSS looks unusual if you are used to kebab-case. It has practical benefits:
- Dot access works, so editors can autocomplete and rename keys.
- Dynamic lookups like
styles[variant]use the same names as your props. - There is no tooling configuration to remember.
The cost is that CSS written this way differs from the usual convention in plain CSS files. If your team shares style rules between modules and global stylesheets, that inconsistency can bother people.
Option 2: kebab-case and bracket access
Kebab-case keeps the CSS idiomatic. In JSX you pay with brackets and quotes:
<button className={styles['btn-primary']}>Save</button>Bracket access is also what you need whenever the key is computed at runtime. The following works with either naming style, as long as the prop values match the class names exactly:
import styles from './Alert.module.css';
export function Alert({ tone = 'info', children }) {
return <div className={styles[tone]}>{children}</div>;
}With tone="warning", this reads styles.warning. If the CSS file has no .warning class, the result is undefined, and React renders the element with no class attribute. Nothing throws and nothing is logged.
Letting the bundler convert names for you
Some tools can convert kebab-case class names into camelCase keys at build time. You then write kebab-case in CSS and use styles.cardFooter in JavaScript.
In Vite, set css.modules.localsConvention:
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
css: {
modules: {
localsConvention: 'camelCase',
},
},
});The option accepts four values:
| Value | Keys exported for `.card-footer` |
|---|---|
| `'camelCase'` | `card-footer` and `cardFooter` |
| `'camelCaseOnly'` | `cardFooter` only |
| `'dashes'` | `card-footer` and `cardFooter` (only dashes are converted) |
| `'dashesOnly'` | `cardFooter` only (only dashes are converted) |
The webpack css-loader has a similar option, modules.exportLocalsConvention, with the values as-is, camel-case, camel-case-only, dashes and dashes-only. The default differs between versions of css-loader, and in some versions it interacts with the namedExport option. Check the documentation for the version you have installed.
Next.js uses its own built-in configuration, which exports class names as written, so with Next.js you rely on camelCase in the CSS or on bracket access.
What counts as an exported name
Only local class selectors become keys. A few cases surprise people:
- A class used in several rules is exported once.
.buttonand.button:hoverproduce a singlebuttonkey. - Compound selectors export each class.
.button.primaryproduces bothbuttonandprimary. - Classes wrapped in
:global(...)are not exported, because they are not renamed. - Element selectors, such as
h2, and IDs are not class names and have no effect on the object's class keys. - With
composes, the value for a key contains several generated names separated by spaces. You still use a single key from JavaScript.
You can list the keys of any imported module to see what you have:
import styles from './Card.module.css';
console.log(Object.keys(styles));This is a quick way to confirm that a name was exported and to see its exact spelling.
Choosing names that age well
Whichever style you pick, a few habits help:
- Name classes after the role inside the component, such as
title,footerorprimary, not after the look, such asblueText. The file is already scoped, so a prefix likecardis redundant. - Keep variant class names equal to the prop values that select them. Then
styles[variant]works without a lookup table. - Avoid names that clash with JavaScript habits. A class called
constructor,toStringorhasOwnPropertycan interfere with ordinary object behavior, so avoid those words in a CSS Module. - Do not depend on the generated value. Strings like
Card_card__x7Kq2change between builds and configurations. Tests and selectors should never hard-code them.
A worked example
This module uses a camelCase convention and a variant selected by a prop:
/* Badge.module.css */
.badge {
display: inline-block;
padding: 0.125rem 0.5rem;
border-radius: 999px;
font-size: 0.75rem;
}
.statusOk {
background: #dcfce7;
color: #166534;
}
.statusError {
background: #fee2e2;
color: #991b1b;
}import styles from './Badge.module.css';
const statusClass = {
ok: styles.statusOk,
error: styles.statusError,
};
export function Badge({ status, children }) {
return (
<span className={`${styles.badge} ${statusClass[status] ?? ''}`}>
{children}
</span>
);
}The lookup table keeps the prop values (ok, error) independent of the class names. That makes it safe to rename a class later. It also gives one place to add a fallback when status has an unexpected value. The ?? '' stops the string undefined from being added to the class list.
Exercise
Your CSS Module contains .error-message. A teammate writes <p className={styles.error-message}>, and the paragraph is unstyled. Why does this fail, and what are two ways to fix it?
Show answer
In JavaScript, styles.error-message is parsed as styles.error - message, a subtraction, so the class is never read. One fix is bracket access: styles['error-message']. The other is to rename the class to .errorMessage in the CSS file and use styles.errorMessage. A third option is a bundler setting such as Vite's localsConvention: 'camelCase', which also exports errorMessage.
Exercise
A component renders <div className={styles[tone]}> and tone is "success", but the CSS Module defines only .info and .warning. What does the element's class attribute contain, and how would you notice the problem?
Show answer
styles.success is undefined, so React renders the div without a class attribute. No error is thrown. You would notice it by inspecting the element in the browser dev tools and seeing no class, or by logging Object.keys(styles). Adding a fallback such as styles[tone] ?? styles.info makes the behavior explicit.