Strategies for handling `module.scss` in React and Next.js development

I feel completely lost.

Just to provide some background, I am working with Next and React.

// package.json
  "dependencies": {
    "@netlify/plugin-nextjs": "^3.4.2",
    "next": "^10.0.0",
    "postcss-flexbugs-fixes": "^5.0.2",
    "postcss-preset-env": "^6.7.0",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-onclickoutside": "^6.11.2",
    "react-svg": "14.0.0"
  },
  "devDependencies": {
    "classnames": "^2.2.6",
    "sass": "^1.34.0"
  }

To test production locally, I use

npx next build && npx next start -p 4000
. Everything works smoothly in development using netlify dev -e.

However, strange effects occur when I have two imports of .module.scss, causing the client-side javascript to cease functioning.

For example, I have a page:

// /pages/test.js
import CompA from 'components/comp-a'
import CompB from 'components/comp-b'

And:

// /components/comp-a.js
import styles from 'components/comp-a.module.scss`

As well as:

// /components/comp-b.js
import styles from 'components/comp-b.module.scss`

This scenario displays correctly visually, but no client-side javascript functions are working without any visible errors. I spent the entire day troubleshooting by commenting out various components and lines of code to pinpoint this issue.

By commenting out one component import in the page, the client-side js works fine, but not with two.

Similarly, when I comment out the styles import in one of the components, the client-side js starts functioning properly as well.

In another situation where it doesn't work:

// components/comp-a.js
import styles from 'components/comp-a.module.js'
import CompB from 'components/comp-b.module.js'

It works if I comment out either the style or the sub-component.

None of these solutions make sense because in the page, I also have the Layout being imported, which contains its own styles and that works perfectly fine.

What could possibly be the cause of all this confusion?

Edit: Upon further investigation, I discovered that I was using @extend .class-abc along with @import 'style/foo.module';, and the .class-abc contained another class:

// /style/foo.module.scss
.class-abc {
  ...
  .bar { 
    ...
  }
}

Strangely, commenting out .bar resolved the issue. I'm utterly puzzled by what is happening.

Answer №1

Utilizing css/scss modules offers a key advantage by keeping styles closely tied to the component and automatically namespacing everything. Therefore, importing component styles into your page is not common practice. To enhance organization, consider restructuring as follows:

- components/
  - comp-a/
    - index.js
    - index.module.scss
  - comp-b/
    - index.js
    - index.module.scss
- pages
  // If test.js does not have its own styles
  - test.js
  // Or if test.js utilizes its own css/scss modules
  - test
    - index.js
    - index.module.scss

Your components and pages structure would then appear as:

// comp-a
import styles from "./index.module.css"

export default function MyCompA() {
  return (<div className={styles.someClass}>I have local comp-a styles</div>)
}

// comp-b
import styles from "./index.module.css"

export default function MyCompB() {
  return (<div className={styles.someClass}>I have local comp-b styles</div>)
}

// test
import MyCompA from "../components/comp-a"
import MyCompB from "../components/comp-b"

// If this also has its own styles
import styles from "./index.module.scss"

export default function MyCompTestPage() {
  return (
    <>
      <p className={styles.someClass}>I have local test page styles</p>
      <MyCompA />
      <MyCompB />
    </>
  )
}

Sharing Styles Between Components

For multiple components requiring the same styles, you can opt to (a) extract those styles to a global stylesheet or (b) consolidate that common code into its own component or (c) share the stylesheet between components. Consider this example for option c:

- components/
  - comps-ab/
    - comp-a.js
    - comp-b.js
    - index.module.scss
- pages
  - test.js
// comps-ab/comp-a
import styles from "./index.module.css"

export default function MyCompA() {
  return (<div className={styles.someClass}>I have shared comps-ab styles but still local to these components</div>)
}

// comps-ab/comp-b
import styles from "./index.module.css"

export default function MyCompB() {
  return (<div className={styles.someClass}>I have shared comps-ab styles but still local to these components</div>)
}

// test
import MyCompA from "../components/comps-ab/comp-a"
import MyCompB from "../components/comps-ab/comp-b"

export default function MyCompTestPage() {
  return (
    <>
      <MyCompA />
      <MyCompB />
    </>
  )
}

In this scenario, both components draw from the same stylesheet, yet it remains localized to these two components without manual inclusion in the test.js page.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to include an icon with dropdown menu options?

I am facing an issue with a text box and modifier dropdown. I want to display an icon representing the current choice when selected. However, using UNICODE for icons causes them not to display properly in certain browsers like Google Chrome unless specific ...

Error encountered with React Hooks - TypeError

What I Aim to Achieve Our goal is to utilize Next.js to create a button named 'ConnectMetamask' that, upon clicking, triggers the predefined hooks and stores the value in a variable called 'userSigner'. This functionality is implemente ...

Patience is key when programming automated scrolling with Selenium or Protractor

My application features a button that, when clicked, uses JavaScript to scroll the page. However, I'm encountering an error stating "Element is not clickable at point (somepoint,somepoint)". I believe this issue arises because selenium/protractor does ...

Is it feasible in ES6 Javascript to access properties or methods of the superclass in a child class without the necessity of utilizing the "this" keyword?

Exploring Javascript ES6: Accessing Parent Class Properties in Child Class class Animal { constructor() { this.sound = 'roar' this.species = 'lion' } } class Lion extends Animal { constructor() { ...

The jQuery .accordion() feature is not functioning properly due to the failure to load jQuery into the HTML document

I have exhaustively researched online and visited numerous resources, including Stack Overflow. Despite making countless adjustments to my code, it still refuses to function properly. The frustration is mounting as I struggle with jQuery - a technology tha ...

When the enter key is pressed, the form will be submitted and the results will be displayed in a modal window without

Behold, my unique form! It lacks the traditional <form></form> tags. <input id="query" name="query" style="font-size: 18pt" id="text" data-email="required" type="text" placeholder="Search Here from <?php echo $row['no']."+"; ?& ...

What are the potential disadvantages of relocating the login logic from the 'signIn()' function in NextAuth.js?

My experience with NextAuth.js for the first time has led me to realize that signing in using the Credentials provider can be a bit tricky when it comes to error handling. It seems like the default implementation should resemble something along these lines ...

It appears that the width of RaFormInput is consistently set at 256 pixels

I am encountering an issue with a tabbed form where the width of the parent form is consistently set to 256px regardless of the content (grids, boxes, etc) that I try to incorporate. It seems that the culprit is the html element MuiContainer-root RaFormIn ...

Tips for capturing text input from a Quill rich text editor div

My attempt to retrieve the content entered in Quill editor's editor div using jQuery codes is not proving successful. Although it works for other text inputs, it fails to do so for the editor div. Below is a demonstration of the issue: $(function() ...

Struggling to make input:checked feature function properly

I'm in the process of developing a product page and I'd like to implement a feature where clicking on the Buy button triggers a pop-up menu to appear. I've been attempting to use the Checkbox hack to achieve this but have encountered some di ...

The functionality of JQuery stops functioning once ajax (Node.js, PUG) is integrated

I've been attempting to incorporate a like feature on my blog post website. When I click on the likes count, it's supposed to trigger an ajax call. In my server.js file, there's a function that handles the POST request to update the number ...

CSS: Dynamically adjusting height based on parent element's current height

I'm seeking clarification on the topic at hand. Why am I unable to simply use the following code: <div style="min-height: 100vh"> <div style="height: 100%"> </div> </div> When I implement this code, ...

Exploring the functionality of dynamic component imports in jest testing

Under a specific condition, I dynamically imported a component and stored it in an object property. Then, I displayed it in the template using vue <component :is="">. Everything is functioning correctly at the component level. However, I am ...

The element is not occupying the full width within the div container

I'm working with a div that contains some elements. My goal is to have these elements span the entire width of the container div. .container { height: 100px; width: 100px; display: flex; flex-direction: column; overflow: scroll; borde ...

PHP code cannot be executed due to a problem with Angular routing

I stumbled upon this previous discussion during my search for assistance with a particular problem, but unfortunately there were no responses that could provide a solution. The issue I am facing involves submitting a form and expecting to receive a php va ...

What is the best way to combine two JavaScript objects?

One object I am currently working with resembles the following structure let ob1 = { 'item_data':{ 'stack':{ 'purchase':'12345', 'order':'22222' } } } Additionally, I have anothe ...

Adjust the margin of a child div based on the parent's width, with the use of JavaScript

Currently, I am developing a website at and I am interested in replicating the layout of another site. The site I would like to emulate is , which features multiple sections with child divs that have margins around them. In order to achieve this effect o ...

React Native and Gradle encounter issues with reading data from the Binary store, resulting in an error message that states (.gradle/.tmp/gradle7278112572988587194.bin offset 230266 exists? true

Yesterday, my React Native code built successfully. However, today I encountered a Gradle error. * What went wrong: Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'. > Could not resolve all dependencies for config ...

What is the best way to utilize CSS to center an element in relation to the scroll bar?

For a group project, I successfully centered a div on a webpage. However, I ran into an issue where the website's contents are centered taking the scroll bar width into consideration. This means that the web page contents adjust to be centered without ...