Skip to content

How to detect Dark Mode reactively? #1274

Answered by herronelou
herronelou asked this question in Q&A
Discussion options

You must be logged in to vote

I ended up wrapping my DarkMode component inside another component which installs a MutationObserver and updates a svelte store:

<script lang="ts">
    import { DarkMode } from 'flowbite-svelte';
    import { isDarkTheme } from '$lib/stores/theme';
    import { onMount } from 'svelte';

    const updateTheme = () => {
        isDarkTheme.set(document.documentElement.classList.contains('dark'));
    };

    onMount(() => {
        updateTheme();

        // Make a mutation observer to watch for class changes on ownerDocument.documentElement
        // and update the theme accordingly
        const darkModeObserver = new MutationObserver((mutations) => {
            mutations.forEach((mutat…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by herronelou
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
1 participant