Can dynamic CSS imports be unloaded in a React application?

I am facing an issue with loading two files using 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 // check if user is valid
          ?
          <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 refers to a component (login) inside the DefaultLayout component.

Situation:

When the user is not logged in, I display the DefaultLayout component containing the login component, which also imports cssFile1.css.

Once the user enters credentials and logs in, they are directed to a path within my PrivateRoute that contains cssFile2.css.

The challenge here is unloading cssFile1.css after the user logs in. Is it possible, and if so, how can this be achieved?

Answer №1

While this approach may not be the most efficient, have you considered scoping all the CSS within the cssFile1.css file? This means writing rules that target elements only if they are inside a specific container with a class like 'cssFile1'.

Similarly, the second CSS file could target elements only if they are contained within a class named 'cssFile2'.

By changing the main container class, you can easily "unload/switch" the CSS and apply the respective rules.

Another helpful tip is that if you're using SASS/LESS, simply enclosing the rules within a container will ensure all rules are scoped upon compilation.

Answer №2

By the end of 2022, a new CSSStyleSheet web API has been introduced to allow complete control of styles through JavaScript, including unloading. To implement this in a React app, you can utilize css-in-js by adjusting the css-loader options in webpack.

You have the ability to:

import darkStyles from '../scss/main/dark.css-style-sheet.scss';
import lightStyles from '../scss/main/light.css-style-sheet.scss';

// Mount one of these onto the DOM
document.adoptedStyleSheets = [darkStyles]
sheet.disabled = true;

Although it may seem complex, I have detailed the process in a blog post on integrating it with react:

Essentially, craco (or eject) needs to be used to establish a new rule that defines exportType: 'css-style-sheet' for css-loader.

Answer №3

I have discovered a clever technique to achieve this in React. Essentially, you can utilize lazy loading of React components that contain the import './style.css' statement. Upon loading, you can then capture the imported StyleSheet in order to toggle its StyleSheet.disabled property at a later stage.

Take a look at my original solution for this issue.

For more information, view this Gist.

Answer №4

It seems that it is indeed impossible as Webpack imports CSS when React compiles. However, you could explore using CSS-in-JS libraries like Aphrodite as an alternative solution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering React hooks: A guide to effectively updating and rendering elements

Each time I click the delete button, it seems to only remove the last element instead of the specific one based on index. Is there a better way to achieve this without changing from <input defaultValue={name} /> to <input value={name} /> in t ...

showing the values stored in local storage

My goal is to show only the values stored in local storage, excluding the key value that displays all data after submitting the login form. welcome <span id="demo"></span>; <script> document.getElementById('demo').innerHTML = ...

Container contents are spilling out of control after adjusting container height to auto

I'm facing an issue on my webpage where the text overflows the container div, even after setting the height to auto. Here's how the page is structured: <html> <head> <body> <div id="wrapper"> <div id="inner_wrapp ...

best way to eliminate empty p tags and non-breaking spaces from html code in react-native

How can I clean up dynamic HTML content by removing empty <p> tags and &nbsp? The whitespace they create is unwanted and I want to get rid of it. Here's the HTML content retrieved from an API response. I'm using the react-native-render ...

The ReactJS/Express landing page fails to display upon initiating the server.js file

Is there a way to set home as the landing page? I'm unsure of how to connect server.js to my landing page or if I should link to App.js instead. Currently, when I execute node server.js through the command prompt, it displays the following. My React c ...

Using jQuery to retrieve the text content of child elements

Struggling to extract the text of child elements using jQuery. I've been at this for a couple of days and can't seem to make it work. If anyone could spare a moment to review, I would greatly appreciate it! SCRIPT: function generateRemoveSect ...

Executing NodeJS custom middleware to show parent function being called

Goal: Showcase the parent function of a middleware function shared = require('./RoutFuctions'); app.post('/link', shared.verifyToken, (req, res) => { ... } In the middleware function exports.verifyToken = functio ...

React-dnd enabling drag-and-drop functionality with Mui DataGrid

Previously, I had experience working with a mui treeview that was easy to expand using react-dnd since each treeitem was a react component. However, when it comes to a datagrid, the rows are made up of JSON objects and not react components anymore. Is the ...

Embracing Interfaces Over 'any' Types in TypeScript

https://i.stack.imgur.com/W6NMa.pngWould it be beneficial to utilize an interface as a variable type rather than opting for any? For instance, if I have 3 functions where I am declaring variables that can contain alphanumeric data, would defining them us ...

Error encountered: The module '@material-ui/core/styles' does not export 'alpha'

I recently encountered an issue while attempting to utilize the material-ui/lab date picker. Even after updating my material-ui version by executing npm install @material-ui/core@latest, I was unable to resolve the error. While this update fixed other is ...

Angular-oauth2-oidc does not successfully retrieve the access token when using OAuth2 and SSO

Here's an issue I'm facing: I've been attempting to integrate SSO and OAuth2 flow using angular-oauth2-oidc. When testing with POSTMAN and ThunderClient in VS Code, I managed to receive the correct response (the access_token). However, I am ...

Employing the html.validationmessagefor to display a client-side error notification

My text fields have server-side validation messages. The field 'title' is a required field on the server side with a '[Required]' data attribute in the class, but it only seems to be checked on a postback or form submit. I am saving the ...

CSS for Page Header with Scroll-Over Content

Having trouble creating a "collapsing header" design where the page content scrolls over the banner image. I've tried adjusting z-index and positioning properties in CSS, but can't achieve the desired effect. Any help or guidance would be greatly ...

passing arguments during deferred resolve() and when() operations

I am currently working on a flash card website and I need to determine the status of preloaded images once they have finished loading or if there was an error. After obtaining the status of each image, I will proceed with further actions. My code is inspi ...

What is the best way to create dynamic transparency based on cursor position?

Is there a way to create an animation like the one on https://meetwalter.com, where the transparency changes with the cursor's position? I previously attempted a similar implementation using CSS, but it seems that the website accomplishes this effect ...

I have noticed that there are 3 images following the same logical sequence, however only the first 2 images seem to be functioning correctly. Can you help

Update: I have found a solution that works. You can check it out here: https://codepen.io/kristianBan/pen/RwNdRMO I have a scenario with 3 images where clicking on one should give it a red outline while removing any outline from the other two. The first t ...

``I encountered an issue with React and Vite when trying to execute the 'npm run dev

npm run dev [email protected] dev vite unable to find configuration file at C:\Users\vyask\Desktop\8th sem internship\mern-blog\client\vite.config.js error encountered while attempting to start dev server: Error ...

What is the procedure in AngularJS to obtain an ID from a URL? My current approach involves utilizing Restangular for communication with REST APIs

I have been successfully using Restangular to retrieve data from the backend. The URLs I was hitting used to provide the data in the following format: For example, when I hit http://mysite/responses/, the responses were in the following structure: [ ...

React-admin CheckboxGroupInput automatically selects certain checkboxes upon loading

How can I set some checkboxes to be checked by default? <CheckboxGroupInput source="my_junction_table" choices={choices} optionText={<KioskCheckbox />} initialValue={[{ id: 4, checked: true }]} // no effect defaultValue={[{ id: 4, check ...

Issue with Vue.js: routes are not found upon page refresh

Here is a basic vue-routing example: const Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar</div>' } const routes = [ { path: '/foo', component: Foo }, { path: '/ba ...