Last active
June 23, 2020 16:43
-
-
Save viclafouch/08e76fe57fbebfb89ee9263fe9de406f to your computer and use it in GitHub Desktop.
A custom React Hook to help you implement a "light/dark mode" component for your application.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
html[data-theme='dark'] { | |
--text-color: #f0F0F0; | |
--background-body: #1C1C1C; | |
--other-var: #111111; | |
} | |
html[data-theme='light'] { | |
--text-color: #111111; | |
--background-body: #FAFAFA; | |
--other-var: #ffffff; | |
} | |
body { | |
color: var(--text-color); | |
background-color: var(--background-body); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// hooks/use-theme.js | |
import { useState, useLayoutEffect } from 'react' | |
const preferDarkSchema = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches | |
const defaultTheme = preferDarkSchema ? 'dark' : 'light' | |
function useTheme() { | |
const [theme, setTheme] = useState(localStorage.getItem('theme') || defaultTheme) | |
useLayoutEffect(() => { | |
document.documentElement.setAttribute('data-theme', theme) | |
localStorage.setItem('theme', theme) | |
}, [theme]) | |
return { theme, setTheme } | |
} | |
export default useTheme |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment