Last active
July 1, 2019 09:01
-
-
Save nukbal/b74cc3c22868032fa73aebba7aa42dce to your computer and use it in GitHub Desktop.
dark mode support with styled-components
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
import React, { lazy, useState } from 'react'; | |
import { ThemeProvider } from 'styled-components/macro'; | |
import lightTheme from 'theme/light'; | |
import darkTheme from 'theme/dark'; | |
export default function Router() { | |
// fallback for lightTheme | |
const [theme, setTheme] = useState(lightTheme); | |
useEffect(() => { | |
function changeTheme(e: any) { | |
if (e.matches) { | |
setTheme(darkTheme); | |
} else { | |
setTheme(lightTheme); | |
} | |
} | |
// https://caniuse.com/#search=prefers-color-scheme | |
const md = window.matchMedia('(prefers-color-scheme: dark)'); | |
md.addListener(changeTheme); | |
changeTheme(md.matches); | |
return () => { | |
md.removeListener(changeTheme); | |
}; | |
}, []); | |
return ( | |
<ThemeProvider theme={theme}> | |
<div>Hello theme mode!</div> | |
</ThemeProvider> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment