ThemeToggle
TheThemeToggle component provides a button to switch between dark and light themes with localStorage persistence and support for Astro’s View Transitions.
Import
Props
Whether this toggle is being used in a mobile menu. When
true, the component uses different element IDs to avoid conflicts with the desktop toggle.Usage
Desktop Header
Mobile Menu
Features
LocalStorage Persistence
The component automatically saves the user’s theme preference tolocalStorage under the key "theme":
Icon Management
The component uses Lucide icons to display the appropriate icon based on the current theme:- Dark mode active: Moon icon visible
- Light mode active: Sun icon visible
hidden/block) for smooth transitions.
View Transitions Support
The component is fully compatible with Astro’s View Transitions API. Event listeners are properly re-attached after each navigation:Analytics Tracking
Theme toggles are tracked using Umami analytics with device context:Implementation Details
Theme Application
The theme is applied by setting adata-theme attribute on the root <html> element:
Element IDs
To prevent conflicts between desktop and mobile toggles, the component uses different IDs based on theisMobile prop:
| Element | Desktop ID | Mobile ID |
|---|---|---|
| Button | theme-toggle | theme-toggle-mobile |
| Moon icon | moon | moon-mobile |
| Sun icon | sun | sun-mobile |
Event Listener Deduplication
The component uses a custom propertyhasListener to prevent duplicate event listeners from being attached:
Styling
The component uses utility classes for styling:theme-toggle-btn class or adding additional classes.
Accessibility
The button includes anaria-label for screen readers:
Default Theme
The component defaults to dark mode if no theme is stored in localStorage:Complete Example
Base.astro
Header.astro
Related Components
- Header - Main navigation bar that includes the theme toggle
- LanguageSwitcher - Companion component for switching languages
CSS Variables
The theme system uses CSS variables defined insrc/styles/global.css. See the Design System documentation for a complete list of theme-aware variables.