React global SCSS: class styling not working

Viewed 2948

I am using React with SASS.

For my components, I am using modular CSS, however, in my Layout.js file, I want to use a main.scss file.

My main.scssfile is working as when I add style to selectors such as body {} or p {}, they style these elements. It's the styles for classes that aren't seeming to come through. For instance, in my global.scss file, I have the following css

body {
  margin: 0;
}
.marginsContainer {
  width: 90%;
  margin: auto;
  padding: 100px;
}

The body is working. The .mainContainer isn't.

I am trying to use .mainContainer in my Layout.js file, like so

import Navbar from './Navbar';
import Head from 'next/head';
import '../global-styles/main.scss';

const Layout = (props) => (
  <div>
    <Head>
      <title>Practise Site</title>
    </Head>
    <Navbar />
    <div className="marginsContainer">
      {props.children}
    </div>
  </div>
);

export default Layout;

What might be the problem here?

1 Answers

Are you using css-modules?

In that case, css-modules adds a hash at the end of the class name. You can avoid it by switching to the global scope for your class.

:global {
  .marginsContainer {
    width: 90%;
    margin: auto;
    padding: 100px;
  }
}

A better solution is to use the class name with the hash, by importing the stylesheet like this.

import styles from '../global-styles/main.scss';

And setting the class name like this.

<div className={styles.marginsContainer}>
Related