Search code examples
reactjssassnext.jscss-modules

SCSS modules not loading in NextJS


I'm not sure what the problem is, as I've done this numerous times with no issues, so I'm thinking I messed something up. I'll show the Product.js component, and the module file, and please let me know if there's anything else I'm missing (for example, there's no next.config.js file either).

Thanks in advance!

Product.js

import { Card } from '@material-ui/core'
import styles from '../styles/Products.module.scss'

export default function Product({ product }) {
  console.log(product)
  return(
    <Card className="product">
      <img src={product.main_image} />
      {product.name && product.name}
    </Card>
  )
}

Products.module.scss file

.product {
  max-width: 300px;

  & img {
    width: 100%;
  }
}

Solution

  • when using CSS module you should pass to className your styles object, and accessing the desired class:

    import { Card } from '@material-ui/core'
    import styles from '../styles/Products.module.scss'
    
    export default function Product({ product }) {
      console.log(product)
      return(
        <Card className={styles.product}>
          <img src={product.main_image} />
          {product.name && product.name}
        </Card>
      )
    }
    

    this because CSS Module will generate an unique class name. Its class name won't be product, but something like [filename]\_[classname]\_\_[hash] (with a unique hash) to avoid name collision.

    adding CSS module