Theme Toggle for Astro
Controls for switching between light and dark color modes within a Astro website.
Installation
bunx --bun shadcn@latest add @gnostic/theme-togglenpx shadcn@latest add @gnostic/theme-togglepnpm dlx shadcn@latest add @gnostic/theme-toggleCopy the files
src/components/ui/theme-toggle/index.tssrc/components/ui/theme-toggle/theme-provider.astrosrc/components/ui/theme-toggle/theme-toggle.astrosrc/components/ui/theme-toggle/theme-toggle.tssrc/components/ui/theme-toggle/types.ts
Setup
The theme toggle requires one ThemeProvider in your document’s <head>. The provider applies the initial mode before the page appears and saves theme preferences. The toggle and browser API report an error when no provider is present.
Add the provider to your layout’s head section:
---
import { ThemeProvider } from "@/components/ui/theme-toggle"
---
<html>
<head>
<ThemeProvider />
<!-- other head elements -->
</head>
<body>
<!-- your content -->
</body>
</html>
Render ThemeProvider before the visible page. Its inline script applies the initial theme early, using the approach documented in the shadcn Astro dark mode guide.
The CSS uses .dark for dark mode. By default, the provider sets data-theme
to light or dark and keeps the root .dark class in sync. System changes,
saved preferences, and toggle actions use the same update.
Set attributeType="data-mode" to use a different data attribute. Set
attributeType="class" to update only the class, or attributeType="none" for
events without root changes. Use the browser API to request a theme change;
the provider does not watch external changes to data attributes.
Replace the old attributeType="attribute" and attributeType="both" values
with attributeType="data-theme", or omit the prop to use that default.
Usage
import { ThemeToggle } from "@/components/ui/theme-toggle"
<ThemeToggle />
Examples
Use Cookie storage
The ThemeProvider allows customizing the storage mechanism for the theme preference.
---
import { ThemeProvider } from "@/components/ui/theme-toggle"
---
<ThemeProvider
storage="cookie"
storageKey="color-mode"
defaultTheme="light"
attributeType="data-theme"
/>
View transition
Set effect on the existing ThemeProvider to choose the default view transition. The prop defaults to undefined, so mode changes have no animation unless the provider or a toggle supplies an effect. The provider includes the transition styles; they apply only while data-theme-vt is set on the document root.
---
import { ThemeProvider, ThemeToggle } from "@/components/ui/theme-toggle"
---
<html>
<head>
<ThemeProvider effect={{ variant: "blast", start: "toggle" }} />
</head>
<body>
<ThemeToggle />
</body>
</html>
reveal opens a clip from the start point. blast grows a circle from that point. Set blur to soften the new theme as the effect opens.
<ThemeProvider effect={{ variant: "reveal", start: "bottom-up", blur: true }} />
start: "toggle" uses the toggle that was clicked. The other start values are top-left, top-right, bottom-left, bottom-right, center, and bottom-up.
The effect is skipped when the browser has no View Transitions API, and when the user prefers reduced motion.
Each toggle can override the provider effect. Omit the prop to inherit the provider setting. Use false to skip it:
<ThemeToggle effect={{ variant: "reveal", start: "center" }} />
<ThemeToggle effect={false} />
Checkbox or switch
With a ThemeProvider on the page, add data-theme-toggle to a native checkbox.
Use role="switch" on that input if it represents an on/off switch.
Checked means dark mode. To start an effect from a wrapper, put the marker and
data-theme-effect on a span that contains the checkbox. Use one marker per control.
A label gives the control a name and lets the user click its text.
Browser API and events
The provider binds controls with [data-theme-toggle] on page load and after Astro navigation.
It removes its listeners before a page swap.
The provider also removes its listeners on astro:before-swap, before Astro
replaces the page during client navigation. theme:before-change runs before a
requested mode change. A mode change does not replace the page.
Each provider run sends the internal theme:provider-dispose event. The old
provider uses it to remove its listeners. The transition runner uses it to cancel
a pending animation. This prevents duplicate listeners and an old animation from
changing the mode after the provider has been replaced. Application code does not
need to send this event.
Import browser functions from theme-toggle.ts:
<script>
import { create, createThemeToggle, setTheme } from "@/components/ui/theme-toggle/theme-toggle.ts"
// Bind controls added by your own script. Existing controls are skipped.
const controllers = create()
// Get or create the controller for one button.
const button = document.querySelector<HTMLButtonElement>("#color-mode")
if (button) {
const toggle = createThemeToggle(button)
toggle.setTheme("dark", { effect: { variant: "blast", start: "center" } })
// Call toggle.destroy() before your script removes this button.
}
// A theme change without a button uses the same events and provider.
setTheme("system", { effect: false })
</script>
create(scope) returns only the controllers it creates. createThemeToggle(button)
returns an existing controller when the button is already bound. Each controller
has theme, setTheme(), toggle(), and destroy().
| Event | Purpose |
|---|---|
theme:before-change |
Bubbles from the source control, or fires on the document for setTheme(). Call preventDefault() to cancel. Set detail.effect to choose an effect for this change. |
theme:apply |
Runs on the document inside the transition update. The provider applies and saves detail.theme, then sets detail.resolvedTheme. |
theme:set |
Runs on the document after the theme is applied. All toggles update their state. |
When a toggle reads the theme, it sends an internal theme:read event with an empty detail object.
The provider fills in the resolved theme and its optional effect before the call returns.
A toggle or a call to setTheme() needs a provider on the same document.
For the three events in the table, event detail includes theme, optional source, and optional effect.
theme:set also includes resolvedTheme (light or dark).
The events do not stop other listeners. Use setTheme() or a controller to
request a change through the full event sequence.
document.addEventListener("theme:before-change", (event) => {
if (event.detail.source?.id === "color-mode") {
event.detail.effect = { variant: "blast", start: "toggle", blur: true }
}
})
document.addEventListener("theme:set", (event) => {
console.log(event.detail.resolvedTheme)
})
Alternate Icon
Pass icons in the slot. Use dark:hidden on the light icon and hidden dark:block on the dark icon when the two marks differ.
Notes
ThemeToggleis a two-state light and dark switch.ThemeProviderreads the saved preference first and falls back to thedefaultTheme. The default value,system, follows the system color scheme.- If you need a richer theme picker, build that separately on top of the same
.darkclass convention.
API Reference
ThemeToggleProps
effect?ThemeEffect | false
Override the page effect for this control. Use false to skip it.
ThemeEffect | falseThemeProviderProps
effect?ThemeEffect
Default effect for requested theme changes. Omit to change mode without animation.
ThemeEffectundefinedstorageKey?string
The key used in the selected storage.
string"theme"defaultTheme?Theme
The theme to use when no saved preference is found.
Theme"system"storage?'localStorage' | 'sessionStorage' | 'cookie'
The storage to use for storing the theme preference. - `localStorage` - stored in the user's browser until cleared manually - `sessionStorage` - stored in the user's browser until the session ends (tab closed) - `cookie` - stored in a session cookie
'localStorage' | 'sessionStorage' | 'cookie'"localStorage"attributeType?'class' | `data-${string}` | 'none'
The root attribute used to report the resolved theme. - `data-*` - set this attribute to light or dark and sync the `dark` class - `class` - sync only the `dark` class on the root element - `none` - emit theme events without changing root attributes
'class' | `data-${string}` | 'none'"data-theme"ThemeEffect
Options for the provider’s effect prop and per-toggle overrides. This is a type, not a component.
variant?ThemeEffectVariant
Animation variant.
ThemeEffectVariant"reveal"start?ThemeEffectStart
Where a reveal or blast effect starts.
ThemeEffectStart"toggle" - the coordinate of the theme toggle that was activatedblur?boolean
Blur the new theme as the effect opens.
booleanfalseWhen to use Theme Toggle
Use ThemeToggle where a user can change the page color mode. Keep its control in a stable location, such as the header. It changes color mode rather than choosing a complete palette.
Keyboard and behavior
Give the control a useful accessible name and check keyboard activation. Verify the chosen mode after page navigation. The rest of the page must also use theme tokens for the change to remain consistent.
Theme and layout
Check images, borders, and focus rings in both modes. Fixed light backgrounds in page content can defeat the theme even when the toggle itself works.