How to use CSS modules in Next.js



Image not found!!

In Next.js, CSS Modules provide a way to scope styles to a specific component or module, preventing style leakage and naming conflicts. Here's a step-by-step guide on how to use CSS Modules in Next.js:

1. Install Dependencies

Make sure you have Next.js installed. If not, you can create a new Next.js project using the following command:

bash
npx create-next-app my-next-app
cd my-next-app

2. Create a CSS Module

Create a new CSS file for your component/module. Name it with the .module.css extension to indicate that it's a CSS Module. For example, if your component is named MyComponent, create a file named MyComponent.module.css:

css
/* MyComponent.module.css */ .container { max-width: 800px; margin: 0 auto; } .title { color: blue; }

3. Use CSS Module in your component

Import and use the CSS Module in your component. Make sure to use the styles object to access the class names:

jsx
// MyComponent.js import React from 'react'; import styles from './MyComponent.module.css'; const MyComponent = () => { return ( <div className={styles.container}> <h1 className={styles.title}>Hello, CSS Modules!</h1> </div> ); }; export default MyComponent;

4. Automatic Class Name Generation

When you use CSS Modules in Next.js, the class names are automatically generated and scoped to the component. The generated class names are hashed, which helps prevent naming conflicts.

5. Run your Next.js app

Now, run your Next.js app using the following command:

bash
npm run dev

Visit http://localhost:3000 in your browser, and you should see your component styled using the CSS Module.

Additional Tips:

  • Make sure that your Next.js version supports CSS Modules. In recent versions, CSS Modules are supported out of the box.

  • If you're using TypeScript, you might need to create a declaration file for your CSS Modules. For example, create a file named MyComponent.module.css.d.ts:

    typescript
    // MyComponent.module.css.d.ts declare module '*.module.css' { const content: { [className: string]: string }; export default content; }

    This helps TypeScript understand the types of the imported styles.

That's it! You've successfully set up and used CSS Modules in a Next.js project.