Is it possible to unload dynamic css imports in react?

Viewed 3062

I have two files which i load with react.lazy and suspense:

import React, { Suspense, lazy }  from "react";
import { Route, Redirect } from 'react-router-dom';
const MainLayout = lazy(()  => import('Components/Layout/MainLayout'))

export const PrivateRoute = () => (
  <Route  render={() => {
    return (
      localStorage.getItem('user')  != null// validation that it is a valid user
          ?
          <Suspense fallback={<div>Loading...</div>}>            
          <MainLayout/>
          </Suspense>
          : <Redirect to={{ pathname: '/login'}} />)
  }} />
)

Second:

import React, { Suspense, lazy } from "react";
const DefaultLayout = lazy(()  => import('Components/Layout/DefaultLayout'))

export const PublicRoute = () => (
    <Suspense fallback={<div>Loading...</div>}>            
        <DefaultLayout/>
    </Suspense>
  )

the /login path is refrencing a component (login) that is inside of the DefaultLayout component.

Scenario:

When the user is not logged in I load the DefaultLayout component which in turn contains my login component which imports cssFile1.css.

When the user enters the credentials i forward them to a path that is contained in my PrivateRoute where in turn i have cssFile2.css

The problem here is that cssFile1.css was loaded when i was using the loginpage but when the user logs in i want to unload cssFile1.css, is this possible and if yes then how?

3 Answers

Ok, This might not be the most optimum approach, but can't the whole CSS inside the cssFile1.cssbe scoped? As in all the rules are written targetting elements if they are inside a certain container with a class say 'cssFile1'.

Likewise the 2nd CSS file will target all the elements only if they are located inside a container with the class 'cssFile2'.

now all you have to do to "unload/switch" the css is changing the main container class and the respective CSS rules will apply.

One last tip is, if you are using SASS / LESS its just a matter of enclosing the rules inside a container and all the rules will be scoped upon compilation.

If I understand right, then no, it's impossible, because of Webpack imported css when React compiled, anyway, you can try to css in js libs, such a Aphrodite.

Related