Only importing styles specific to each component on each route

Viewed 78

Is there a way to only import the styles specific to each component in React? Looking at the code below, the styles from both the "Home" component as well as the "Dashboard" component are imported into App.js. So when you navigate to /Home, you see the styles that were imported from Dashboard and vice versa.

In other words, when navigating to a component, is there a way for it to only inherit its own styles and not other styles which are automatically imported by importing other components?

Home.js

import '../Styles/css/style.css'

class Home extends Component {
   ....
}

App.js

import {Dashboard} from './Components/Dashboard/Dashboard';
import {Home} from './Components/Home';

class App extends Component {
  render() {
    return (

      <React.Fragment>
          <Router>     
              <Switch>
                <Route exact path="/Home" component={Home} />
                <Route path="/Dashboard" component={Dashboard}/>
              </Switch>
           </Router>
      </React.Fragment>

    );
  }
}
1 Answers

Why you don't use Styled Component ? Recently I used this in a project, I had separated and segmented style for each component that do not affect each other. https://www.styled-components.com/

Related