I have 2 css files: light.css and dark.css, also have a ThemeSwitch component which represents the select element, this element has handler for handling change of value (the value is either light or dark). The question is: is there any way to include one of these css files according to the ThemeSwitch value: if value is light - import/include light.css, if value is dark - then import/include dark.css (like a theme switcher)
-
You could do something like this: erikmartinjordan.com/select-css-variable-reactAndrew Hulterstrom– Andrew Hulterstrom2022-08-26 20:38:53 +00:00Commented Aug 26, 2022 at 20:38
-
@Andrew Hulterstrom. I've tried this, but it works only if you need to choose theme once at the start, but I want to be able to switch them during the runtime no matter how much timesYura Shtefanko– Yura Shtefanko2022-08-26 20:54:36 +00:00Commented Aug 26, 2022 at 20:54
-
Oh, so you just want to be able to turn off one of the files at a time? Maybe this answer would be helpful: stackoverflow.com/a/1598917/15351640Andrew Hulterstrom– Andrew Hulterstrom2022-08-26 20:56:59 +00:00Commented Aug 26, 2022 at 20:56
Add a comment
|
1 Answer
You can use react-lazy or react-suspense libraries for conditionally changing components or CSS files.
Below is the example of react-lazy library
import React, { useLayoutEffect, useState } from "react";
const Theme1 = React.lazy(() => import("./Theme1"));
const Theme2 = React.lazy(() => import("./Theme2"));
const THEME_1 = "1";
const THEME_2 = "2";
export const ThemeSelector = ({ children }) => {
const [theme, setTheme] = useState(null);
const changeTheme = () => {
debugger;
setTheme(theme === "1" ? "2" : "1");
};
useLayoutEffect(() => {
setTimeout(() => {
if (theme !== THEME_2) {
setTheme(THEME_2);
} else {
setTheme(THEME_1);
}
}, 5000);
}, []);
return (
<>
<React.Suspense fallback={<></>}>
{theme === "1" && <Theme1 />}
{theme === "2" && <Theme2 />}
</React.Suspense>
<button type="checkbox" value={theme} onClick={changeTheme}>Change Theme</button>
{children}
</>
);
};
1 Comment
Yura Shtefanko
It looks like a solution, but the dynamic import gives an error:
Cannot find module './css/dark.css' or its corresponding type declaration