Next.js Discord

Discord Forum

Do you need to use SCSS module every time in NextJS?

Unanswered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
I'm trying to understand how to import SCSS in NextJS. If I have some code that uses SCSS as such:

const Hero = () => {

    return (<section className={`${styles["main"]}`}>Hero

        <div className={styles["main_background"]}></div>

        <div className="main_left"></div>
        <div className="main_right"></div>


    </section>);
}


Must I go through every single element adding classname={${styles["class_01"]}}. Is there a simpler way to make this less repetitive? Or is this the standard practice to use SCSS in NextJS?

7 Replies

You can create a global style sheet, import it in _app and then write CSS to select the elements you want to target.
I wouldn’t myself. I only have custom properties at that level. But it sounds like what you want.

The general idea with Nextjs for the last few years was to always have global and local styles. CSS modules e.g. a file that ends in .module.scss in this case, ensures no class collisions, that’s why it is recommended. But that means importing the file and then you have access to the CSS/SCSS using object notations.

I normally do this:
import s from "./file.module.scss"

Then apply like:
<div className={s.main}>

not like this:
<div className={s[main]}>
If you’re talking about chaining multiple classes, there’s a package called clsx: https://github.com/lukeed/clsx which makes that easy.

There are only 2 simple options for styling like this, global and local, so yes, manually.
I wrote a guide on how to use clsx with css modules and next.js: https://morganfeeney.com/guides/nextjs/how-to-style-with-nextjs-css-modules

Ultimately you'll end up doing something like this:

import clsx from 'clsx';
import s from "./Example.module.css";

const Example = ({ children }) => {
  return <p className={clsx(s.root, s.whatever_class, "global-utility")}>{children}</p>;
};

export default Example;