ThemeProvider.js 757 B

1234567891011121314151617181920212223242526272829
  1. import React from 'react'
  2. import { ThemeContext, themes } from '../contexts/ThemeContext'
  3. const getTheme = () => {
  4. const theme = `${window?.localStorage?.getItem('theme')}`
  5. if (Object.values(themes).includes(theme)) return theme
  6. const userMedia = window.matchMedia('(prefers-color-scheme: light)')
  7. if (userMedia.matches) return themes.light
  8. return themes.dark
  9. }
  10. const ThemeProvider = ({ children }) => {
  11. const [ theme, setTheme ] = React.useState(getTheme)
  12. React.useEffect(() => {
  13. document.documentElement.dataset.theme = theme
  14. localStorage.setItem('theme', theme)
  15. }, [ theme ])
  16. return (
  17. <ThemeContext.Provider value={{ theme, setTheme }}>
  18. {children}
  19. </ThemeContext.Provider>
  20. )
  21. }
  22. export default ThemeProvider