Skip to content

DarkThemeToggle

Bryce Russell edited this page Jan 24, 2023 · 13 revisions

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

Features

  • 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

When do I use this?

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

How to use

---
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>

Props

hide?: boolean

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

...attrs

Type: HTMLAttributes<'button'>

All other props passed to this component are passed as attributes to the toggle button (id, class, style, aria-label, ...)

Examples

Persist theme without button

Add this to pages where the theme should persist without any visible toggle buttons

<DarkThemeToggle hide />

Using with <IconSwitcher>

---
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>
Clone this wiki locally