ThemeProvider.js 1008 B

1234567891011121314151617181920212223242526272829303132333435363738
  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(
  7. '(prefers-color-scheme: light)')
  8. if (userMedia.matches) return themes.light
  9. return themes.dark
  10. }
  11. const ThemeProvider = ({ children }) => {
  12. const [ theme, setTheme ] = React.useState(getTheme)
  13. React.useEffect(() => {
  14. document.documentElement.dataset.theme = theme
  15. localStorage.setItem('theme', theme)
  16. }, [theme])
  17. document.documentElement.classList.add('theme-transition')
  18. document.documentElement.setAttribute('data-theme', theme)
  19. window.setTimeout(function() {
  20. document.documentElement.classList.remove('theme-transition')
  21. }, 100)
  22. return (
  23. <ThemeContext.Provider value={{ theme, setTheme }}>
  24. {children}
  25. </ThemeContext.Provider>
  26. )
  27. }
  28. export default ThemeProvider