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

Comment options

You must be logged in to vote
1 reply
@0xd-0
Comment options

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