1

I have component A and component B.

component A.js

import React from 'react'
import './A.css'

export default class A extends React.Component {
   ....
} 

component B.js

import React from 'react'
import './B.css'

export default class B extends React.Component {
   ....
}

App.js

import React from 'react'
import ReactDOM from 'react-dom'
import { Route, Switch, BrowserRouter } from 'react-router-dom'
import A from './A'
import B from './B'

ReactDOM.render(
  <BrowserRouter>
    <Switch>
        <Route exact path='/A' component={A}/>
        <Route exact path='/B' component={B}/>
      </Switch>
  </BrowserRouter>,
  document.getElementById('root'));

When I visit /A it load a.css and b.css and vice versa. Is there way to render respective components CSS only when component is rendered on its route?

Marmik Desai
  • 104
  • 11
  • It sounds like you have different rules with the same selector in those components, and loading both CSS files overwrites some of the rules in one of them? Is that the actual problem you're having? –  Jul 05 '18 at 13:15
  • yes, addition I don't want to load component B css when Component A render. – Marmik Desai Jul 05 '18 at 13:21
  • Regarding the CSS issue, you can add a class to your main wrapping element: `
    ...
    `, then put `.compA` in front of all your CSS selectors.
    –  Jul 05 '18 at 13:23
  • Is there any way around without changing classname? I found this way but not sure it is right? render() { import('./SampleComponent.css'); } – Marmik Desai Jul 05 '18 at 13:25
  • Just try it out then. It's a good thing anyway if your questions already contains attempts you made on your own. –  Jul 05 '18 at 13:27
  • I am wondering what is best way practice. – Marmik Desai Jul 05 '18 at 13:29
  • Do you find any way to do that? – Nisarg Thakkar Sep 03 '18 at 08:54
  • render() { import('./SampleComponent.css'); ---> This solution looks not working in react 18 and webpack 4... any idea about alternatives? – Rama Rao M Jul 19 '23 at 17:56

1 Answers1

0

In such case, you can make use of styled components for component-specific styling.

Piyush Zalani
  • 3,686
  • 1
  • 13
  • 29