Home > database >  React imports CSS from other components
React imports CSS from other components

Time:07-17

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?

CodePudding user response:

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 {
  ...
}

Edit:

While the information above is indeed the nature of CSS, there are apparently available tools for automating the scoping with unique identifiers. See references in other answers.

CodePudding user response:

Since there is no built-in scoping mechanism to limit CSS Rules to specific components, This behavior is completely normal, Which results in all your div elements in the component tree to be effected by this import.

I would recommend using CSS Classes to have a layer of scope at least semantically.

<div className="hero-container">
  // nested jsx...
</div>

And then add CSS rules in your hero.css file:

.hero-container {
  // css-rules
}

create-react-app toolchain has a concept called CSS Modules, If you happen to be using this toolchain, checkout official documentation of CSS Modules here.

Since all our CSS is bundled into a single index.css file at the end of the day, It's harder to maintain distinct class names in larger projects. So, it's better to use a more elegant solution like CSS Modules or third-party libraries that style our components in a tightly coupled fashion, like styled-components etc.

CodePudding user response:

That because you apply the CSS as global.when you are importing in css like import './Home.css';.So it is apply as global. If you need to apply CSS styles as scope to component, you can use different options as below.

One option. you can use module.css file. According to the official repo.“CSS files in which all class names and animation names are scoped locally by default”.In here you are you can declare styles using classes. but this is not supported to css id.so always to remember declare classes inside the module.css file. let's deeper in to this. let say I have declare home.module.css file as this.

.home{
background:green

}

then you cam import this to your jsx file as below and apply this class as below.

 import homeStyles from './home.module.css';
 
 export const Home= () => {
   return (
     <section className={homeStyles.home}>
       module.css example
     </section>
   );
 };

when looking at the code you can get idea that I have declared variable by this line," import homeStyles from './home.module.css';".and I am accessing that class inside the section div using homeStyles.home.That because homeStyles is a object that contain the home class property.

Second Option

You can use Styled components. See official doc.This is a third party library. but has much resources to adding and modifying the styles. if you are use, Maetrial ui V5 It also used the this styled component styling pattern.(Just check material ui v5 Styled hook).This styling pattern is not used in the previous material ui versions. The One important this is we can use css classes and css ids for styles the our react elements.

Let say we need to style div with class home which has css propety to background green. we can style this as below.

import styled from "styled-components";
const sectionWrapper = styled.div`
  .home {
    background: green;
  }

  @media screen and (max-width: 600px) {
    .home {
      background: red;
    }
  }
`;

export const Home = () => {
  return (
    <sectionWrapper>
      <div className="home">module.css example</div>
    </sectionWrapper>
  );
};

As in the module.css file, we can use media queries in the styled component as well. I have add a media query in the example as well. It explain s that screen size less than 600px,that home class div make background red. You can get better idea about this from their official site. see

  • Related