The DarkMode component is a user-friendly theme switcher designed to toggle between light and dark modes effortlessly. It ensures an optimal user experience by adapting the interface to different lighting conditions or personal preferences.
About
This component is accessible, and easy to integrate into any project. It leverages TailwindCSS's darkMode configuration to provide seamless theme transitions, making it an essential tool for creating modern, responsive applications.
Example
Start by importing the DarkMode component from the theui-svelte library. Here’s how to use the DarkMode component in your application:
<script>
import { DarkMode } from "theui-svelte";
</script>
<DarkMode />
This will render a theme switcher that toggles between light and dark themes.
System Default Theme
You can seamlessly adopt system color schemes to manage the theme using the systemDefault
feature. By default, systemDefault
is set to true
, which means the app will initially load with the user's device color scheme (light or dark). The theme can then be switched between dark and light as needed.
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.
This flexibility allows you to provide a user-friendly and adaptive experience tailored to individual preferences.
<script>
<DarkMode systemDefault={false} />
</script>
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.
<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:
<DarkMode class="bg-brand-primary-500/20 text-brand-primary-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 can be activated with the
Enter
orSpace
key, ensuring full keyboard navigation.
Best Practices: Use the aria-label
attribute for clear message to the screen readers. By default, the value is "Toggle light or dark mode".