1. Install required packages
npm install next react react-dom
2. Enable CSS modules support
Next.js supports CSS modules out of the box. Simply name your CSS files with the .module.css extension, and Next.js will recognize them as CSS modules.
For example, if you have a component named Button, you can create a corresponding CSS module file named Button.module.css.
3. Write your CSS
In your CSS module file (Button.module.css in this example), you can write your CSS as usual. Here’s an example:
/* Button.module.css */
.button {
background-color: blue;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
}
.button:hover {
background-color: darkblue;
}
4. Import and use CSS module in your component
In your React component file (Button.js), import the CSS module and apply the classes as you would normally:
// Button.js
import styles from './Button.module.css';
const Button = () => {
return <button className={styles.button}>Click me</button>;
};
export default Button;
5. Use scoped styles
When you import and use a CSS module class in your component, Next.js will automatically generate unique class names, ensuring scoped styles.