'React Component SCSS available for all Components
I just started learning ReactJS and I made a Project with .scss
For some reason when I add a style in a .scss
file that style also changes other components' styles as well.
example: I add a li style in the Home.scss, but it will change the style of the Footer component's li too. I didn't import it into the Footer.js or anything.
Does anyone know what is the reason why does it do it, and what is the solution?
Solution 1:[1]
Add a class footer in the first div of footer component
sass allows nested defining of classes like
.footer{
li{
}
}
using that can help. since it doesn't matter where you import scss in react. styles are imported globally by default.
Solution 2:[2]
Adding a className
per component won't solve your problem, it will work as expected until you have any nested component.
Because if you add
#component-name {
li {
...
}
}
The CSS will be applied to any component inside of that component too.
To limit your CSS to a component in react, you have a few options :
CSS Modules
Create React App supports CSS Modules out of the box (as of version 2)
It works with SCSS too (YourComponent.module.scss
)
YourComponent.js
:
import styles from './YourComponent.module.css'
export const YourComponent () => {
<ul>
<li className={styles.yourLi}>
</ul>
}
YourComponent.module.scss
:
.yourLi {
color: blue;
}
CSS-in-JS
With this method, as the name suggests, you can declare your CSS within your JS. There are multiple libraries to implement this.
Styled-Components
Here is an example with styled components which is the one that seems to be the most used as of today:
const YourLi = styled.li`
display: inline-block;
border-radius: 3px;
padding: 0.5rem 0;
margin: 0.5rem 1rem;
width: 11rem;
background: transparent;
color: white;
border: 2px solid white;
`
render(
<div>
<ul>
<YourLi>
Your styled li
</YourLi>
</ul>
</div>
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | satyam |
Solution 2 |