While using react-router for a multi-page react app, I've found that the different components that are to be rendered based on the path display the stylesheets in those components, even when the corresponding component isn't displayed.

I was playing around with adding a Sponsors page to my website, and the CSS was behaving strangely. Digging deeper into the problem with chrome devtools, I found that the css from my homepage was on the page while it was not being displayed, causing unexpected styles.

I've tried researching if this is the expected behaviour without any luck. I removed the homepage from my routing code and the styles behaved as expected in the other component, proving that that import was the problem.

My routing code:

          exact path="/" 
          render={props => <MainPage language = {this.state.language}/>}
          render={props => <Sponsors language = {this.state.language}/>}

Of course with

import Sponsors from './Pages/Sponsors/Sponsors.js'
import MainPage from  './Pages/MainPage/MainPage.js';

at the top of that file.

and at the top of MainPage.js:

import './MainPage.css';

An import that looks like that, and the same type in Sponsors.css.

Any code in that MainPage.css will affect the elements in the Sponsors component, even when the url is at /Sponsors (i.e. the MainPage component shouldn't be rendering).

I'm looking to ensure I understand the behaviour of react-router, that the MainPage.css should not appear when MainPage is not being rendered. As an alternative I could write specific enough css that this never happens, but It was my understanding that the modular nature of react featured that not being a necessity, as in I can write it only specific enough for the code being rendered. Am I mistaken?

1 Answers

pankaj kumar On

I understood you are trying to limit the scope of CSS to a module, generally it is having a global scope. you can use "CSS Modules", to overcome this behaviour.

please find the article from facebook. https://facebook.github.io/create-react-app/docs/adding-a-css-modules-stylesheet

hope it will help to fix the issue.