What are the best methods for preventing scss styles from leaking between pages?

I'm currently working on a project that includes the following files:

/* styles/1.scss */
body {
  /* Some other styles not related to background-color */
}
/* styles/2.scss */
body {
  background-color: blue;
}
// pages/one.js
import "../styles/1.scss";

export default ()=>(
  <div>Hello, One!</div>
)

Upon visiting localhost:3000/one, I noticed that the background turns blue even though no style for background-color is defined in 1.scss!

I suspect this issue might be related to css modules, so I attempted wrapping 2.scss with :local. I also tried renaming 2.scss to 2.module.scss, but it did not fix the problem.

Any suggestions on how to resolve this? I appreciate your assistance!

Edit: You can view this issue on codesandbox: https://codesandbox.io/s/priceless-flower-oswh1

If the background color is not orange, try clicking "Go to two" and then return to one. The orange background will persist.

Answer №1

When styling the body element or providing css resets, global styles are necessary.

Method 1:

// one.js
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>{`
      body {
        background-color: red;
      }
    `}</style>

    Hello, One!
    <Link href="/two">
      <a>Go to two</a>
    </Link>
  </div>
);

and

// two.js
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>{`
      body {
        background-color: orange;
      }
    `}</style>

    Hello, Two!
    <Link href="/one">
      <a>Go to one</a>
    </Link>
  </div>
);

You can alternatively store the style in a separate file and import it as needed.

Method 2:

// styles/one_style.js
import css from "styled-jsx/css";

export default css.global`
  body {
    background-color: red;
  }
`;

and

// one.js
import globalStyles from "../styles/one_style";
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>
      {globalStyles}
    </style>

    Hello, One!
    <Link href="/two">
      <a>Go to two</a>
    </Link>
  </div>
);

Code Sandbox

I trust this information will be beneficial to you.

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

Error: Surprising token found in ReactJS application on CodeSandbox

Encountering an unexpected token on line 5 error in my ReactJS project when testing it on CodeSandbox. Interestingly, the app runs smoothly without errors on my local machine. import React, { Component } from 'react'; import Header from ' ...

JQuery user interface dialog button

When using a jQuery UI dialog, I want to add tooltips to buttons. In my current code: buttons: { 'My Button' : function(e) { $(e.target).mouseover(function() { alert('test'); }); } This code triggers an action only a ...

Tips for positioning three child divs horizontally within a parent div with flexible dimensions and arranging each one separately

Is there a way to stack three divs horizontally within a fluid-width container div, with each child div scaling proportionally when the browser is resized for responsive design? The left-most div should be on the left, the middle div centered, and the righ ...

Exploring ways to retrieve the result of a function within Next.js?

I'm in the process of creating a website using Vercel and Next.js. The initial step involved utilizing a template from Next.js. One of the functions within my project is responsible for extracting strings from a Google Sheets spreadsheet. This partic ...

Maintaining the proportions of images in different screen sizes when resizing

I apologize if this question has already been addressed, but I have been unable to find a solution that works for my specific issue. My Gallery consists of a side list of available images in one section, which when clicked changes the image source in anot ...

What's the most effective method for identifying a pattern within a string of text?

For the sake of honing my skills, I undertook a practice task to identify patterns of varying lengths within a specified string. How can this function be enhanced? What potential issues should I address in terms of optimization? function searchPattern(p ...

Customizing the jQuery Datepicker to only allow a predefined set of dates

I am looking for assistance regarding the jQuery datepicker. I have an array of dates and I need to disable all dates except for the ones in this specific array. Currently, the code I have does the opposite of what I need. I generate the array of dates in ...

An unanticipated issue has arisen with the Alert Open Error. The command "browser.switchTo().alert().accept();" functions properly in Firefox, but encounters difficulties in Chrome while executing via Jenkins

Seeking assistance on how to resolve a specific error encountered in the Chrome browser while using Protractor. https://i.stack.imgur.com/7Fm4l.png The error message reads as follows: "UnexpectedAlertOpenError: unexpected alert open: {Alert text : There a ...

Updating model values while dragging with Angular Dragular

Currently, I am experimenting with dragula and its newer version, dragular, on some sample projects. One specific dilemma I am facing involves the implementation of drag and drop functionality in an Angular project. My query pertains to utilizing a list o ...

An issue has occurred: TransformError SyntaxError: Unexpected keyword 'const' was encountered

While practicing programming with React-Native, I encountered a problem that I couldn't figure out how to solve. I attempted to use solutions from various forums, but none of them worked. import { StyleSheet, Text, View, Image } from 'react-nativ ...

I keep receiving a 400 (Bad Request) error when trying to delete with my REST API

I've successfully created an API and have managed to make POST and GET requests work flawlessly. However, I'm facing some trouble with the DELETE request. Every time I try to execute it, I encounter a 'DELETE http://localhost:3000/api 400 (B ...

Display tables side by side using Material-UI

Presently, I am utilizing NextJs and MaterialUI to display a table with data fetched from an API created in Strapi. Challenge The current issue lies in using a table component with props that are imported into a page, where the props are mapped to an API ...

``How can I extract the last string in Vue.js when working with string processing?

I've been working with strings in vuejs and currently have 4 URL strings: https://web-sand.com/product/slug/apple-iphone-13 https://web-sand.com/product/slug/samsung-galaxy https://web-sand.com/product/slug/xiaomi-red https://web-sand.com/product/slug ...

Problem with character encoding in Node.js

I am encountering an issue while retrieving data from a request, as the formatting or encoding is not matching my requirements. Attempted to address this by setting the encoding with req.setEncoding('utf8') The expected string should appear as: ...

One way to dynamically track if any radio buttons in a group have been selected is by utilizing JQuery

Even though there are many related resources for this question, I still need a flawless solution. I have dynamically generated five groups of radio buttons. Each group contains up to five radio buttons. I have separately validated "none checked in" and "a ...

Navigating the issue of "Experiencing additional hooks rendered compared to the previous render"

I'm currently in the process of developing a small application where certain elements will be nested within one another. My approach involves segmenting each component into its own file (children), returning a function with two components in each Rend ...

Error occurs in Query component when using a higher order component (HOC) due to element type

I've developed a custom higher-order component called withInfiniteScroll, designed to enable infinite scrolling functionality for a basic list of data. My aim is to integrate this HOC within Apollo's Query component, but I'm encountering an ...

Troubleshooting a Vue 2 component's prop receiving an incorrect value

I'm currently working on creating a menu that navigates between categories. When a category has a sub-category, it should return a boolean value indicating whether it has a sub-category or not. <template> <select><slot></slot ...

Beautiful prompt interface for HTML

I'm attempting to create a sweet alert using the HTML option: swal({ title: "HTML <small>Title</small>!", text: "A custom <span style="color:#F8BB86">html<span> message.", html: true }); Instead of just text, ...

tips for passing value to the date field using proctractor

This is the HTML code I am working with: <input id="filter-datepicker" type="daterange" ranges="ranges" class="form-control date-picker" placeholder="Select Date Range" name="sensorDetails.date" ng-model="myDateRange" ranges="ranges" requi ...