Switching between dark and light mode in Ant Design

I have successfully implemented dark mode toggling in my application. However, when I try to switch back to light mode, the CSS does not seem to be reloading properly.

Below is the code snippet:

//ThemeContext.jsx
const DarkTheme = lazy(() => import("./dark-theme"));
const LightTheme = lazy(() => import("./light-theme"));

export const ThemeContext = createContext(null);

export const ThemeContextApp = ({ children, ...rest }) => {
  const [theme, handleToggle] = useTheme();
  return (
    <ThemeContext.Provider value={{ theme }} {...rest}>
      <Switch
        checkedChildren="Dark Mode"
        unCheckedChildren="Light Mode"
        checked={theme === "dark"}
        onChange={(checked) => {handleToggle(checked);}}
      />
      <Suspense fallback={<span />}>
        {theme === "dark" ? <DarkTheme /> : <LightTheme />}
      </Suspense>

      {children}
    </ThemeContext.Provider>
  );
};

This is my index.js

import React from "react";
import ReactDOM from "react-dom";
// import "./index.css";
import App from "./App";
import { store } from "./app/store";
import { Provider } from "react-redux";
import * as serviceWorker from "./serviceWorker";
import "antd/dist/antd.css";
import "react-toastify/dist/ReactToastify.min.css";
import { ThemeContextApp } from "./Components/Theme/ThemeContext";

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <ThemeContextApp>
        <App />
      </ThemeContextApp>
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

This is my dark theme

//DarkTheme.jsx

import React from "react";
import "./dark-theme.css";
const DarkTheme = () => <></>;

export default DarkTheme;

This is my light theme

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

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

This is my useThemeHook

import { useEffect, useState } from "react";

export const useTheme = () => {
  const [theme, setTheme] = useState("light");

  useEffect(() => {
    if (window.localStorage.getItem("theme")) {
      let localStorageItem = window.localStorage.getItem("theme");
      setTheme(localStorageItem);
    } else {
      window.localStorage.setItem("theme", theme);
    }
  }, []);

  useEffect(() => {
    let localStorageItem = window.localStorage.getItem("theme");
    if (localStorageItem !== theme) {
      window.localStorage.setItem("theme", theme);
    }
  }, [theme]);

  const handleToggle = (checked) => {
    if (checked) {
      setTheme("dark");
    } else {
      setTheme("light");
    }
    // return window.location.reload();
  };

  return [theme, handleToggle];
};

When switching to Dark Mode, everything works fine. However, upon switching back to Light Mode, the light theme CSS requires a page refresh to take effect. The console shows that the component is rendered, but the light theme CSS is not applied.

https://i.sstatic.net/4syYv.png

Despite the console log message indicating that the light mode has loaded, the CSS styling does not update accordingly.

https://i.sstatic.net/eY1tT.png

Please offer any advice or insights on this issue

Thank you

EDIT:

For the full code, please refer to: https://codesandbox.io/s/antdesignlight-darktheme-gqwlyz?file=/src/components/UseTheme.jsx

Answer №1

One way to manage the state of your `checked` value is by using `useState` as shown below:

export const ThemeContextApp = ({ children, ...rest }) => {
  const [theme, handleToggle] = useTheme();
  const [checked, setChecked] = useState(false);
  return (
    <ThemeContext.Provider value={{ theme }} {...rest}>
      <Switch
        checkedChildren="Dark Mode"
        unCheckedChildren="Light Mode"
        onChange={(checked) => {
          handleToggle(!checked);
          setChecked(!checked);
        }}
      />
      <Suspense fallback={<span />}>
        {theme === "dark" ? <DarkTheme /> : <LightTheme />}
      </Suspense>

      {children}
    </ThemeContext.Provider>
  );
};

For more information on toggling state with React hooks, check out this resource:

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

What's the deal with this occurrence? The width of the HTML window seems

Exploring different html markup and layouts, I stumbled upon this JSFiddle: http://jsfiddle.net/vLJAq/15/. I made some modifications to it, but one thing that puzzles me is why the green box disappears when the window width is reduced? Here's the cod ...

Can the name of a React Component that is nested and inner be retrieved by invoking a function from one of its props?

I am currently working with this particular component: class DashboardPage extends Component { constructor(props) { super(props); this.state = { loading: true, shownPage: ActiveDeals, error: false, errorDetails: null, ...

Changing the color of text in Material UI typography elements

I am new to Material UI and I'm attempting to customize a Typography element with a specific text color: const theme = createMuiTheme({ palette: { text:{ primary: "#FFFFFF" } } }); const CustomText = (props: { text:string, ...

What steps should I take to incorporate the delete feature as described above?

Click here to access the delete functionality Hello there, I need help implementing a delete function similar to the one provided in the link above. Below is the code snippet for your reference. I am utilizing the map method to extract data from an array ...

Twice the clicking actions triggered by the event

Whenever I try to trigger a function by clicking on the label text, the click event seems to be firing twice. HTML <label class="label_one"> Label One <input type="checkbox"/> </label> However, if I modify the HTML code as f ...

Page returning causing tabs to refresh improperly

Today I want to discuss two different pages: VelocityMicro.com/Cruz.php and VelocityMicro.com/PC.php, which I am currently viewing in Firefox. The issue I am experiencing is with Cruz.php. When you click on a tab like "R100 Series" and then select an acce ...

What is the best way to determine the width of tables - in the HTML code or using a CSS class?

I recently came across some advice suggesting that a website should still be able to function properly even if the CSS files are not loaded. What approach do you think would work best in this situation? Would it be more effective to use <table width=50 ...

Adding setTimeout within the Axios Scope can enhance the functionality and performance of your

Show an alert in the catch block of Axios. The issue at hand: Error message does not disappear after the specified time when using setTimeout. ...

Modifications to contenteditable elements result in a change to their IDs

Having some trouble with the behavior of a contenteditable div. The code structure is like this: <div contenteditable="true"> <p id="element-id-1">element-id-1</p> <p id="element-id-2">element-id-2</p> </div> E ...

Is it possible for Tinymce to provide me with precise HTML content that retains all styles (essentially giving me a true WYSIWYG

I find it puzzling how Tinymce is labeled as a WYSIWYG editor when what I see visually is not exactly what I get when I retrieve the HTML using getContent(). It seems more like "what you see is just what you see." Currently, when I use getContent() to get ...

Round progress indicator with directional pointer

I've been working on creating a round progress bar that features an arrow at the front. This is my current progress: HTML Code: <!-- Container --> <ul class="progress"> <!-- Item --> <li data-name="Item 1& ...

How can jQuery be utilized to dynamically update the text in a navbar?

<div id="page1" data-role="page"> <div data-role="header" data-position="fixed" align="center"><img src="img/VAWE-long-300x30-transparent.png" width="300" height="30" alt="" /></div> <div data-role="content" style="margin ...

What is the method for updating a state in react by utilizing the axios.get function?

In my layout, the navbar is a separate component and the rest of the page. The issue arises when I change the showing Classes in the navbar - I want the page to reflect the related information for each class. I have all the necessary info from the navbar ...

What advantages does JWT have over Firebase that make it the preferred choice?

In our authentication systems, we have the option to verify a user through Firebase or by their stored email in the database. Despite having these methods of verification, why do we incorporate JWT (json web token) into our processes? What distinct advan ...

Utilizing Material UI with Appbar logo aligned to the left and Tabs featured at the center

I am currently working on creating a react material ui AppBar. The design includes a logo and tabs, with the tabs supposed to be centered in the AppBar and the logo positioned on the left side. However, I have been facing difficulty in making the logo al ...

How to Align Bootstrap Icons in the Center Horizontally

I'm struggling to center Bootstrap Icons within my buttons. The icon appears to be off-center horizontally, and I've tried various methods like text-align and flexbox with justify-content. It seems like the "letter" itself is causing some extra s ...

Tips for ensuring the pop-up submenu remains visible even when the cursor is outside the parent container and submenu during hover

Is there a way to keep the pop submenu visible even when the mouse hovers outside of its parent container or the submenu? Currently, if the mouse doesn't move straight down from the parent container (B) .account-settings-container to the top arrow of ...

Bootstrap slider with fading in and out effects

I am attempting to create a bootstrap slider that fades in and out when transitioning between slides, similar to the effect demonstrated in this template.. I am using Visual Studio 2010 with ASP.NET. The issue I'm facing is that when the image change ...

How to prevent useEffect from rendering the form script twice during loading?

On my next.js site, I am utilizing a HubSpot form that I would like to render only once on page load. Currently, the form is rendering twice which is not the desired outcome. How can I modify the code to ensure the form renders only on page load? I attemp ...

The function cannot be called on a type that does not have a callable signature. The specified type, 'number | Dispatch<SetStateAction<number>>', does not have any compatible call signatures

Currently, I am working on setting up state to be passed through context in React using hooks. However, when I attempt to use the dispatched state updater function, an error is thrown: Cannot invoke an expression whose type lacks a call signature. Type &a ...