2

In a project, i have different components with different css imports and in the app i use react-router to define the paths. When I access /anycomponent i have their imports in the head, but all the css of the other components also go there. Is there any way to import a component's css only when it is rendered?

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

import component1 from './pages/component1';
import component2 from './pages/component2';

export default function Routes() {
    return (
        <BrowserRouter>
            <Switch>
                <Route path="/" exact component={component1} />
                <Route path="/component2" component={component2} />
            </Switch>
        </BrowserRouter>
    );
}
D. Lobo
  • 69
  • 6
  • Why do you want to do this? Surely it's better to aggregate CSS as much as possible so that when a component renders, you don't have to also load a CSS file? – JMadelaine Apr 03 '20 at 18:59
  • I already have 10 style tags on my head, and i'm not even 5% from the end, i would like to avoid this unnecessary amount of imports on my head. It would improve performance too. – D. Lobo Apr 03 '20 at 19:05
  • How are you styling your components? Are you creating CSS files manually or using some form of CSS-in-JS like Emotion? – JMadelaine Apr 03 '20 at 19:10
  • I'm creating the css files manually, one for each component. – D. Lobo Apr 03 '20 at 19:54
  • 1
    You should really look into using CSS-in-JS such as Emotion, Styled Components, or something similar. If you're creating separate files, you're bloating your repo and making the code harder to maintain. Emotion is great for creating component-specific CSS and Emotion handles all the CSS bundling for you at compile time. – JMadelaine Apr 03 '20 at 21:24

1 Answers1

0

Try lazy loading the component:

const Component1 = lazy(() => import('./pages/component1'));
const Component2 = lazy(() => import('./pages/component2'));

<BrowserRouter>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Component1 }/>
        <Route path="/component2" component={Component2 }/>
      </Switch>
    </Suspense>
</BrowserRouter>
Shota
  • 6,910
  • 9
  • 37
  • 67