Issue
I am having a problem with CSS imports in React, I have a page Home that imports Home.css and a page Hero that imports Hero.css appearently in every page of the application the Hero.css is being applied without even declaring it how can I fix this? These are the following components:
App:
import './App.css';
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Home from './pages/home/Home';
import Hero from './pages/hero/Hero';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />}></Route>
<Route path="/hero" element={<Hero />} ></Route>
</Routes>
</Router>
);
}
export default App;
Hero:
import './Hero.css';
function Hero() {
return <div>
<h1>Hero!</h1>
<button className='glow-on-hover' disabled>test 1</button>
<button className='small-button glow-on-hover'>test 2</button>
<button className='small-button glow-on-hover'>test 3</button>
</div>;
}
export default Hero;
Hero.css:
div {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
justify-items: center;
background-color: #002bff;
}
Home:
import './Home.css';
function Home() {
return <div>
<p>Home!</p>
</div>;
}
export default Home;
The div in the Home component is blue even though the Home.module.css is empty and I declared that the div must be blue only in the Hero.module.css how can I fix this?
Solution
First, it's important to understand that importing CSS into a JS page is not actually a feature that JavaScript has. It's an instruction to a bundler like Webpack to include this CSS in the build process.
Moreover, CSS has no native means of scoping it's effects to a cetain component. It's your responsibility to apply the scoping via a class etc.
For example:
React
return <div className="component-hero">
...
CSS
.component-hero {
...
}
Answered By - Noam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.