'How to make a stylesheet accessible to only one component react.js
I have multiple stylesheets. Let's say navbar.css and footer.css. I want to use the pseudo-element :root in both of these css files to define variables. However, I don't want the variables to be accessible to the other css file. When I use both of these components, the css files merge together and my styles clash. How can I prevent this?
App.jsx
---
import React from "react";
import Navbar from "./Navbar";
import Footer from "./Footer";
export default class App extends React.Component {
render() {
<Navbar/>
<p>blah blah</p>
<Footer/>
}
}
Navbar.jsx
---
import React from "react";
export default class Navbar extends React.Component {
render() {
<div>...</div>
}
}
Footer.jsx
---
import React from "react";
export default class Footer extends React.Component {
render() {
<div>...</div>
}
}
Navbar.css
---
:root {
bg-col: white;
}
Footer.css
---
:root {
bg-col: black;
}
Now, I have shortened these files to keep it simple, but, the bg-col variables clash with each other. How can I fix this?
Solution 1:[1]
You can try with CSS module. In that way, one css file is separate and independent from another. Maybe add a class to that root element and the problem is solved.
Create two files
Navbar.module.css
Footer.module.css
and in your Navbar.jsx and Footer.jsx just import these modules.
Navbar.jsx
---
import React from "react";
import styles from './Navbar.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
export default class Navbar extends React.Component {
render() {
<div className={styles.root}>...</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 | Karlo Tvrdinic |
