Skip to content Skip to sidebar Skip to footer

Sass Id Selector Isn't Working In React And Create-react-library

I have a library I'm making with a Header component and a Button component. I gave them ID's to identify them in my SASS file, this is my current situation: index.js: import React

Solution 1:

You can either rename your scss file to remove the module from file name:

import'./styles.scss'

or if you want to use module pattern in your file name, do this:

import styles form './styles.module.scss'

And provide id / class in this manner:

exportconstButton = ({text, bgColor, textColor, fontFamily}) => {

  return<buttonid={styles.button}style={ // orclassName={styles.myClass1}
    {backgroundColor: [bgColor],
    color: [textColor],
    fontFamily: [fontFamily]}
  }>{text}</button>
}

exportconstHeader = ({text, size, fontFamily, textColor}) => {
  return<h1style={{fontSize: [size],
    fontFamily: [fontFamily],
    color: [textColor]
  }} id={styles.header}>{text} // or className={styles.myClass2}
  </h1>
}

This behavior is usually implemented by bundlers like webpack, browserify etc. It is not an inherent feature of sass.

When you use this module pattern for your sass, the generated stylesheet looks vaguely like this:

.moduleName_className__someUniqueId { // for classescolor: red; 
}

#.moduleName_myId__someUniqueId { // for IDscolor: blue; 
}

What problem does it solve?

It provides you unique selectors (IDs and classnames) by adding moduleName and a unique identifier with them. Which helps you keep your styles organized and separated.

Docs - add css / scss modules.

Solution 2:

I came across the same problem. I am using scss files with module pattern.

The simplest solution I could find is using attribute selector.

This does not work:

#myID {
   color: red;
}

Instead of above code I used below in my module.scss file and worked:

h1[id="myID"] {
   color: red;
}

Post a Comment for "Sass Id Selector Isn't Working In React And Create-react-library"