Search code examples
javascriptreactjsreact-hooksstyling

Switching between Dark and Light Mode in React


I'm using the useDarkMode library in React.

import useDarkMode from 'use-dark-mode'

const DarkModeToggle = () => {
    const darkMode = useDarkMode(false)
    return (
        <>
            {darkMode ? (
                <button type="button" onClick={darkMode.disable}>
                    ☀
                </button>
            ) : (
                <button type="button" onClick={darkMode.enable}>
                    ☾
                </button>
            )}

        </>
    )
}

I want the buttons to switch between the sun and moon, and be able to switch between dark mode and light mode. I can't seem to work out how to do this, I've also tried using hooks to with no luck.


Solution

  • Based on the documentation useDarkMode() returns an object with the properties like value:

    value: A boolean containing the current state of dark mode.

    So most probably you can try with the following:

    {darkMode.value ? (
       <button type="button" onClick={darkMode.disable}>
           ☀
       </button>
    ) : (
       <button type="button" onClick={darkMode.enable}>
           ☾
       </button>
    )}
    

    I hope this helps!