Common Pitfalls with CSS Modules
You'll learn the subtle mistakes that trip up developers when working with CSS Modules—especially around naming and third-party components.
The Kebab-Case Trap
CSS traditionally uses kebab-case for class names (.user-avatar, .nav-header), and CSS Modules honor this convention. However, JavaScript requires bracket notation to access kebab-cased properties:
/* styles.module.css */
.user-avatar {
border-radius: 50%;
}
import styles from './styles.module.css';
// ❌ Awkward and error-prone
<div className={styles['user-avatar']} />
// ✅ Much cleaner with camelCase
<div className={styles.userAvatar} />
The fix: Use camelCase in your CSS Modules (.userAvatar). You get dot notation in JavaScript and cleaner code. Think of it like naming JavaScript variables—you wouldn't write my-variable, so don't write .my-class.
Third-Party Component Styling Challenges
CSS Modules scope styles locally, which creates problems when styling library components:
/* Won't work—library components don't import your module */
.modalOverlay {
background: rgba(0, 0, 0, 0.8);
}
If a third-party component renders its own elements, your scoped classes won't apply. You need either:
- Global selectors with
:global(.actual-class-name)to break out of local scope - Wrapper-based styling where you style a container div
- Component-specific props (className, style) if the library accepts them
It's like trying to decorate someone else's house from inside yours—you need permission or a way to reach outside your boundaries.
Key Takeaway: Stick to camelCase class names in CSS Modules for clean JavaScript syntax, and remember that locally-scoped styles can't directly affect third-party component internals without escape hatches like :global or wrapper patterns.