Importing and Applying Styles
What you'll learn: How to import a CSS Module into your React component and apply its styles using a JavaScript object.
The Import Syntax
Once you've created a .module.css file (as covered in the previous lesson), you need to import it into your component. The import looks like this:
import styles from './Component.module.css';
This statement imports all the class names from your CSS Module as properties of a styles object. The build tool (Vite, in your case) processes this and gives you an object where keys are your original class names and values are the generated, scoped class names.
Applying Classes to Elements
To use these styles, you access properties on the styles object and assign them to the className prop:
function Button() {
return (
<button className={styles.primary}>
Click Me
</button>
);
}
If your CSS Module has a .primary class, you access it as styles.primary. React applies the scoped class name that Vite generated, preventing conflicts with other components.
Multi-Class and Dynamic Patterns
You can combine multiple classes or conditionally apply them:
<div className={`${styles.card} ${styles.highlighted}`}>
Content
</div>
<button className={isActive ? styles.active : styles.inactive}>
Toggle
</button>
Think of it like this: The CSS Module import gives you a "dictionary" where you look up your original class names to get their collision-proof versions. You're still using className, but now the values come from a JavaScript object instead of being hardcoded strings.
Key Takeaway: Import your CSS Module as styles, then apply classes using className={styles.yourClassName} to get scoped, collision-free styling in your React components.