Home > Blockchain >  Why does React randomly chose a different Stylesheet instead the one I imported?
Why does React randomly chose a different Stylesheet instead the one I imported?

Time:04-21

I have a React App with the following folder structure.

folder structure

All my "pages" have their own Folder with a .jsx file and a .css to style the page.

I imported the CSS in the HomePage.jsx like:

import '../HomePage/HomePageStyles.css';  //HomePage.jsx

So far, everything is working just fine. Then I created the ChampionDetailPage.css and imported it in the ChampionDetailpage.jsx like that.

import '../ChampionDetailPage/ChampionDetailPageStyles.css';  //ChampionDetailPage.jsx

Now things start to get funny. The HomePages.jsx suddenly start to use styles from ChampionDetailpage.css that have the same class names without any obvious reason. The goes vice versa, so the ChampionDetailPage.jsx uses classes from the HomePageStyles.css as well.

For example, I have the class .content-right in both .css files

.content-right{  /* HomePage.css */
    width: 55%;
}

.content-right{  /* ChampionDetailStyles.css */
    display: flex;
    padding-right: 20px;
    flex-grow: 100;
    flex-direction: column;
}

In this case, React somehow styles my Homepage.jsx with the ChampionDetailPages.css which is also visible in the Chrome dev tools.

Chrome dev tools

Why does that happen and how do I fix it?

Things I tried already:

  • Changing the import eg. import './ChampionDetailPageStyles.css';

  • Throwing the CSS into its own directory in both cases, the problem remains the same!

Thanks for your help in advance.

CodePudding user response:

You can't have stylesheets with classes that overlap eachothers.

Then, the class that is taken in consideration is the one that was in the css that was loaded the last. This is why you have each of the two classes that are picked up randomly.

What you must know When you import a css this way:

  • Its content is not scoped for your file that imports this css.
  • It will be imported globally, and then, classes that are defined inside will be shared to every dom content of your aplication during its whole lifecycle.
  • You have no control on the order of importation of your css over the time.

To summarize, the stylesheet is not actually picked up randomly, it is the one that happens to be loaded the last that overrides every class that was already defined in the previously loaded css.

Something to know, all the css that you import in your client application are ALL loaded at the bootstrap.

A better way to manage styles with React is to use Emotion. A framework that permits to handle css with your program, and also to be able to scope your styles to your component, or to share it with several components.

  • Related