DarkMode

The DarkMode component is a button that switches the page between light and dark mode. It stores the choice in local storage, so the next visit opens in the same theme.

About

It toggles the dark class on the <html> element, which is what the library's dark variant keys off, so every component follows without any extra work.

Example

Start by importing the DarkMode component from the theui-svelte library. Here's how to use the DarkMode component in your application:

Svelte
<script>
  import { DarkMode } from "theui-svelte";
</script>

<DarkMode />

This will render a theme switcher that toggles between light and dark themes.

System Default Theme

The systemDefault prop decides where the first theme comes from. It is true by default, so the page opens in the device's color scheme until the visitor picks a theme themselves. Once they do, the stored choice wins.

If systemDefault is set to false, the app will load with the light theme by default. Users can still switch to their preferred theme manually after the initial load.

Once the user switches the theme, the choice is saved in localStorage under the theui-theme key and is used on the next visit instead of the system or default theme.

Set it to false and the page always opens in light mode until the visitor switches.

Svelte
<DarkMode systemDefault={false} />

Theme Switch Icon

The DarkMode component comes with a default icon for the dark mode toggle button. However, you can easily replace this icon with your custom design. Simply add your custom SVG or other icon code inside the DarkMode component and the default icon will be replaced. You can use svg icon or theui-svelte's Svg component for this.

   
Svelte
<DarkMode>
   <svg class="dark:fill-yellow-200" ... >
      <path d="M6 .278a.77.77 0 0 ... 0-1.167.242-2.278.681-3.286"/>
   </svg>
</DarkMode>
<!-- or use the Svg component -->
<DarkMode>
   <Svg class="dark:fill-yellow-200">
      <path d="M6 .278a.77.77 0 0 ... 0-1.167.242-2.278.681-3.286"/>
   </Svg>
</DarkMode>

Style Customization

For customization, you can add your own classes to adjust the spacing, alignment, or other styles:

Here's how to use the DarkMode component in your application:
Svelte
<DarkMode class="bg-brand-500/20 text-brand-500 rounded-md p-2" />

Accessibility

The DarkMode Button component toggles between light and dark themes, designed for accessibility.

  • aria-label="Toggle light or dark mode": Provides a clear description for screen readers about the button's function.
  • aria-pressed: Indicates the button's current state (true for dark mode, false for light mode), giving feedback on whether the button is active.
  • Keyboard Accessibility: the button is focusable and responds to Enter and Space.

Best Practices: Use the aria-label attribute for clear message to the screen readers. By default, the value is "Toggle light or dark mode".

Configuration