Load a component's CSS only if it is rendered

Viewed 409

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>
    );
}
1 Answers

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>
Related