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?

8
  • 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? Commented Jul 5, 2018 at 13:15
  • yes, addition I don't want to load component B css when Component A render. Commented Jul 5, 2018 at 13:21
  • Regarding the CSS issue, you can add a class to your main wrapping element: <div className="compA">...</div>, then put .compA in front of all your CSS selectors. Commented Jul 5, 2018 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'); } Commented Jul 5, 2018 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. Commented Jul 5, 2018 at 13:27

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.