Skip to content

Instantly share code, notes, and snippets.

@scott1991
Last active November 12, 2023 09:55
Show Gist options
  • Save scott1991/dc0dac81fb7596d3f54f9cb2c77c8a18 to your computer and use it in GitHub Desktop.
Save scott1991/dc0dac81fb7596d3f54f9cb2c77c8a18 to your computer and use it in GitHub Desktop.
Implementing Local Storage and System Preference Color Mode with React-Dark-Mode-Toggle
import DarkModeToggle from "react-dark-mode-toggle";
import { useState, useEffect } from "react";
function ReactDark() {
const [isDarkMode, setIsDarkMode] = useState(() => {
const theme = localStorage.getItem("theme");
if (theme) {
return theme === "dark";
}
// If theme not found in localStorage, use system prefers setting
return window.matchMedia("(prefers-color-scheme: dark)").matches;
});
// Some divs will not be affected by data-bs-theme because they inherit from body,
// but React can't add data-bs-theme there directly
useEffect(() => {
const theme = isDarkMode ? "dark" : "light";
document.body.setAttribute("data-bs-theme", theme);
}, [isDarkMode]);
const onToggleDarkMode = (newIsDarkMode) => {
setIsDarkMode(newIsDarkMode);
const theme = newIsDarkMode ? "dark" : "light";
localStorage.setItem("theme", theme);
};
return (
<div>
{/* This is the DarkModeToggle component */}
<DarkModeToggle
onChange={onToggleDarkMode}
checked={isDarkMode}
size={80}
/>
</div>
);
}
export default ReactDark;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment