'how to dynamically change global stylesheets in next js

I have two CSS files one for Light theme and other for Dark theme. How to dynamically change the style sheets ?

Here is the code i am currently using in __app.js

import React, { useState, useEffect } from "react";
import "../styles/globals.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";
import { ThemeContext } from "../context/ThemeContext";

function MyApp({ Component, pageProps }) {
  const [theme, setTheme] = useState("light");

  useEffect(() => {
    if (theme == "dark") {
      import("primereact/resources/themes/arya-blue/theme.css");
    }
    if (theme == "light") {
      import("primereact/resources/themes/saga-blue/theme.css");
    }
  }, [theme]);

  return (
    <ThemeContext.Provider value={[theme, setTheme]}>
        <Component {...pageProps} />
    </ThemeContext.Provider>
  );
}

export default MyApp;

This code is working to switch from light theme to dark theme but it fails to switch from dark to light. Is their any better way to do this ?



Solution 1:[1]

The problem is that when switching back to light theme from dark theme your app contains the css of both dark and light themes.

One solution that comes to my mind is to store the theme state in local storage and then reload the page , something like this

Although it has a drawback that upon theme change your website would lose all the other states


import React, { useState, useEffect } from "react";
import "../styles/globals.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";
import { ThemeContext } from "../context/ThemeContext";

function MyApp({ Component, pageProps }) {
  const [theme, setTheme] = useState("light");
  const currentTheme = localStorage.getItem("theme");

  useEffect(() => {
    localStorage.setItem("theme",theme)
    window.location.reload();
  }, [theme]);

  if (currentTheme == "dark") {
      import("primereact/resources/themes/arya-blue/theme.css");
    }
    if (currentTheme == "light") {
      import("primereact/resources/themes/saga-blue/theme.css");
    }

  return (
    <ThemeContext.Provider value={[theme, setTheme]}>
        <Component {...pageProps} />
    </ThemeContext.Provider>
  );
}

export default MyApp;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phil