-
Notifications
You must be signed in to change notification settings - Fork 4
DarkThemeToggle
A dark mode button toggle and script designed for websites with a light(default) and dark theme
Note: This component is for websites with only a light(default) and dark theme, for more advanced theme features like defining multiple themes and scoping themes to a specific element try out the
<MultiThemeToggle>
component
- Create a button with dark/light toggle function
- Add/remove 'dark' class from
<body>
- Persist theme using
sessionStorage
- Listen to system preference changes
- Ability to hide button and keep script for theme persistence
- Add
aria-label
by default, can override
This component is used when you want to have a button toggle between a light and dark theme while also persisting between pages and listening to system preferences
---
import { DarkThemeToggle } from 'astro-headless-ui';
---
<DarkThemeToggle>
Toggle Dark Theme
</DarkThemeToggle>
Output:
<script>
...
</script>
<button onclick="darkThemeToggle()" aria-label="Toggle dark theme">
Toggle Dark Theme
</button>
Stops the button from rendering, but keeps the script. Useful for pages where the dark theme should persist without a toggle button on the page
Type: HTMLAttributes<'button'>
All other props passed to this component are passed as attributes to the toggle button (id
, class
, style
, aria-label
, ...
)
Add this to pages where the theme should persist without any visible toggle buttons
<DarkThemeToggle hide />
---
import { DarkThemeToggle, IconSwitcher } from 'astro-headless-ui';
import { Icon } from 'astro-icon';
---
<DarkThemeToggle style="padding:.5rem;">
<IconSwitcher active="body.dark" size="2rem">
<Icon name="ri:sun-foggy-line"/>
<Icon name="ri:moon-cloudy-line"/>
</IconSwitcher>
</DarkThemeToggle>