Dark mode in react.js
Create ThemeProvider
Create theme-provider.tsx
file and add following code.
import { createContext, useEffect, useState } from "react";
type Theme = "dark" | "light" | "system";
type ThemeProviderProps = {
children: React.ReactNode;
defaultTheme?: Theme;
};
type ThemeProviderState = {
theme: Theme;
setTheme: (theme: Theme) => void;
};
const storageKey = "theme";
const initialState: ThemeProviderState = {
theme: "system",
setTheme: () => null,
};
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
const ThemeProvider = ({
children,
defaultTheme = "system",
...props
}: ThemeProviderProps) => {
const [theme, setTheme] = useState<Theme>(
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme,
);
useEffect(() => {
const root = window.document.documentElement;
root.classList.remove("light", "dark");
if (theme === "system") {
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
.matches
? "dark"
: "light";
root.classList.add(systemTheme);
return;
}
root.classList.add(theme);
}, [theme]);
const providerState = {
theme,
setTheme: (theme: Theme) => {
localStorage.setItem(storageKey, theme);
setTheme(theme);
},
};
return (
<ThemeProviderContext.Provider {...props} value={providerState}>
{children}
</ThemeProviderContext.Provider>
);
};
export { ThemeProvider, ThemeProviderContext };
In your App component add ThemeProvider
import { ThemeProvider } from "./theme-provider";
const App = () => {
return (
<ThemeProvider defaultTheme="system">
...
</ThemeProvider>
)
};
export default App;
Create useTheme hook
Create use-theme.tsx
file and add following code
import { useContext } from "react";
import { ThemeProviderContext } from "./theme-provider";
const useTheme = () => {
const context = useContext(ThemeProviderContext);
if (context === undefined)
throw new Error("useTheme must be used within a ThemeProvider");
return context;
};
export { useTheme };
Create theme toggle
Create theme-dropdown.tsx
and copy the following code.
import {
IconButton,
Menu,
MenuContent,
MenuItem,
MenuTrigger,
} from "@repo/react-ui";
import { IconMoon, IconSun } from "@tabler/icons-react";
import { useTheme } from "./use-theme";
const ThemeDropdown = () => {
const { setTheme } = useTheme();
return (
<Menu>
<MenuTrigger asChild>
<IconButton variant="outline" size="md" colorScheme="black">
<IconSun size={20} className="hidden [html.light_&]:block" />
<IconMoon size={20} className="hidden [html.dark_&]:block" />
</IconButton>
</MenuTrigger>
<MenuContent>
<MenuItem value="light" onClick={() => setTheme("light")}>
Light
</MenuItem>
<MenuItem value="dark" onClick={() => setTheme("dark")}>
Dark
</MenuItem>
<MenuItem value="system" onClick={() => setTheme("system")}>
System
</MenuItem>
</MenuContent>
</Menu>
);
};
export { ThemeDropdown };