Support dark mode in your Svelte apps.
This component sets the theme based on the user’s preferred color scheme using window.matchMedia.
The preferred theme is persisted using the window.localStorage API.
yarn add -D svelte-dark-mode
# OR
npm i -D svelte-dark-mode
The theme
is set to either "dark"
or "light"
based on the user’s system preference.
<script>
import DarkMode from "svelte-dark-mode";
let theme;
$: switchTheme = theme === "dark" ? "light" : "dark";
$: document.body.className = theme; // "dark" or "light"
</script>
<DarkMode bind:theme />
<h1>This is {theme} mode.</h1>
<p>Change the theme and reload the page.</p>
<button on:click={() => (theme = switchTheme)}>
Switch to {switchTheme} mode
</button>
<style>
:global(.dark) {
background: #032f62;
color: #f1f8ff;
}
</style>
When using server-side rendering (SSR), employ the afterUpdate
lifecycle to access document.body
or document.documentElement
.
<script>
import { afterUpdate } from "svelte";
afterUpdate(() => {
document.body.className = theme;
});
</script>
The theme will automatically be updated if the user changes their color scheme preference at the system level.
By default, this component uses "theme"
as the key to persist the theme. Supply your own local storage key using the "key"
prop.
<DarkMode key="custom-theme-key" />
localStorage.getItem("custom-theme-key"); // "dark" || "light"
Prop name | Value |
---|---|
theme | "dark" or "light" (default: "dark" ) |
key | string (default: "theme" ) |
- on:change: dispatched when
theme
is updated
<script>
let events = [];
</script>
<button type="button" on:click={() => (theme = switchTheme)}>
Toggle theme
</button>
<DarkMode
bind:theme
on:change={(e) => {
events = [...events, e.detail];
}}
/>
{events.join(", ")}
svelte
version 3.31 or greater is required to use this component with TypeScript.