Dark Mode with React + Vite
Enable light and dark themes in React + Vite using the class strategy Vinyaas tokens expect. Default follows the device preference.
Vinyaas writes CSS variables for light and dark. Dark styles apply when html has the dark class. Choose another guide from Dark Mode.
Default = system preference
Until the visitor picks light or dark, follow prefers-color-scheme. Do not write a stored preference on first visit — only persist after an explicit toggle.
const stored = localStorage.getItem("vinyaas-theme");
const dark =
stored === "dark" ||
(stored !== "light" &&
window.matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.classList.toggle("dark", dark);Theme tokens
After vinyaas init, your CSS entry (preferred: src/index.css) includes light defaults and a .dark block. Components read those variables — you do not need a separate component theme package.
Toggle the class
Flip appearance by toggling dark on the document element:
document.documentElement.classList.toggle("dark");Persist the choice in localStorage (and optionally a cookie) so navigations and reloads keep the same mode.
Vite wiring
Place a blocking script in index.html (or run equivalent logic before React mounts) that sets dark on <html> from storage or prefers-color-scheme. That avoids a flash of the wrong theme.
<script>
const theme = localStorage.getItem("theme");
const dark =
theme === "dark" ||
(!theme && matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.classList.toggle("dark", dark);
</script>Expose a React toggle that updates the class and localStorage. Ensure your global CSS (for example src/index.css) includes the Vinyaas .dark token block from init.