skip to Main Content

I have the following code.

<Suspense fallback={<span />}>
  {theme === "dark" ? <DarkTheme /> : <LightTheme />}
</Suspense>

DarkTheme.jsx

import React from "react";
import "./dark-theme.css";
const DarkTheme = () => {
  console.log("Dark theme loading...");
  return <></>;
};

export default DarkTheme;

LightTheme.jsx

import React from "react";
import "./light-theme.css";

const LightTheme = () => {
  console.log("light theme loading");
  return <></>;
};
export default LightTheme;

So what happens is when theme changes to dark the DarkTheme component loads, when theme is NOT dark, the LightTheme component loads. Right now the DarkTheme component and its css loads perfectly, however when the theme is NOT dark the LightTheme component loads BUT its css is NOT loaded.

When toggling to dark mode, works perfectly fine.
enter image description here

However toggling back to light, component loads but the css does not load

enter image description here
Full code can be found here https://codesandbox.io/s/antdesignlight-darktheme-gqwlyz?file=/src/components/light-theme.css:1369-1374

2

Answers


  1. You are mixing up css imports with React js conditional rendering!

    Your condition {theme === "dark" ? <DarkTheme /> : <LightTheme />} is only affecting react elements being rendered inside Suspense, however once you import a css stylesheet it stays attached to your DOM, and when you switch the theme state and import another stylesheet you just create a css clash between the light theme and the dark theme.

    One way to achieve switching up dark mode with light mode is to provide conditional style props like :

     <div style={theme === 'dark' ? {background:'black'} : {background:'white'}}>
      {children}
      </div>
    

    Do this in your top level component (App)

    You might wanna take a look at css modules it’ll make your life easier.

    Login or Signup to reply.
  2. I had the same issue before, and I found a solution from this StackOverflow post: Dynamically load a stylesheet with React. However, instead of dynamically loading a CSS file, you might consider only changing the color scheme of your layout.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search