React Styling Approaches Reference
1. Global CSS vs. Component-Specific CSS
- Global CSS: Styles defined in a single file (e.g.,
global.css) that affects all components - Component-Specific CSS: Styles scoped to individual components for better organization and maintenance
a. CSS Modules
- Files named with
.module.cssextension (e.g.,Component.module.css) - Styles are scoped only to components that import them
- Prevent class name collisions by auto-generating unique identifiers
- Imported as JavaScript objects:
import styles from './styles/Resume.module.css' - Classes accessed via object properties:
className={styles.resume}
b. Regular CSS Files
- Files named with
.cssextension (e.g.,Resume.css) - Styles are globally accessible to all components
- Potential for class name collisions
- Imported without variable assignment:
import './styles/Resume.css'
c. Combining Both Approaches
// Using module CSS conditionally
<div className={condition && styles.item}>
// Combining global and module classes
<div className={`container ${styles.item}`}>
d. Stacking CSS Classes
In many cases, you want an element to have multiple classes. There are ways you can achieve this:
- Using String Literals
// common syntax
<div className={`${styles.base_class} ${isActive ? 'active' : ''}`}>
- Using array +
join()The array +.filter(Boolean).join(' ')pattern is worth knowing — it removes falsy values cleanly and scales well when you have 3+ conditional classes.
// For many conditional classes, array + join is cleaner
<div className={[styles.base_class, isActive && 'active', isError && 'error'].filter(Boolean).join(' ')}>
The && Gotcha with Falsy Values
When using condition && styles.item, React renders the condition value if it's falsy but not false. The dangerous case is 0:
// count is 0 — React renders "0" in the DOM, not nothing
<div className={count && styles.active}>
// Safe alternatives:
<div className={count > 0 && styles.active}>
<div className={Boolean(count) && styles.active}>
<div className={!!count && styles.active}>
Rule of thumb: always use an explicit boolean expression, not a raw variable.
Recommended Folder Structure
/src
/components
Component1.jsx
Component2.jsx
...
/styles
Component1.module.css
Component2.module.css
global.css
...