DEV Community

Gurupal Singh
Gurupal Singh

Posted on

Add dark mode in react admin panel

Hi, i am implementing a bootstrap theme to my react admin panel which is having dark mode. I want to add this into my project with prefers-color-scheme (window.matchMedia) and not by toggling. I have 2 bootstrap css files (theme-light.css and theme-dark.css).

Can anyone help me or have an example that how can i implement the dark mode inside my react application ? I have googled and found below code, but it is not working as expected.

const [isDarkMode, setisDarkMode] = useState(false);
const [isLightMode, setisLightMode] = useState(false);
const [supportsColorScheme, setSupportsColorScheme] = useState(false);

useEffect(() => {
const supportsColorScheme = window.matchMedia(
"(prefers-color-scheme)"
).matches;

const isDarkMode = window.matchMedia(
  "(prefers-color-scheme: dark)"
).matches;

const isLightMode = window.matchMedia(
  "(prefers-color-scheme: light)"
).matches;

setisDarkMode(isDarkMode);
setisLightMode(isLightMode);
setSupportsColorScheme(supportsColorScheme);
Enter fullscreen mode Exit fullscreen mode

}, []);

if (supportsColorScheme) {
if (isDarkMode) {
require("assets/css/theme-dark.css");
} else if (isLightMode) {
require("assets/css/theme-light.css");
}
}

Discussion (2)

Collapse
kellskamuzu profile image
Kelvin Chidothi • Edited on

Just curious, why are you using an else if statement when you only have two conditions?

Collapse
gurupal profile image
Gurupal Singh Author

yes removed it. but nothing is working as of now