0
0
mirror of https://github.com/yude-jp/yude.jp synced 2025-01-03 18:10:12 +09:00
yude.jp/pages/components/themeContext.js

53 lines
1.3 KiB
JavaScript

import React from 'react'
const getInitialTheme = _ => {
if (typeof window !== "undefined" && window.localStorage) {
const storedPrefs = window.localStorage.getItem("color-theme")
if (typeof storedPrefs === "string") {
return storedPrefs
}
const userMedia = window.matchMedia("(prefers-color-scheme: dark)")
if (userMedia.matches) {
return "dark"
}
}
// If you want to use light theme as the default, return "light" instead
return "dark"
}
const ThemeContext = React.createContext()
export default ThemeContext
export const ThemeProvider = ({ initialTheme, children }) => {
const [theme, setTheme] = React.useState(getInitialTheme)
const rawSetTheme = theme => {
const root = window.document.documentElement
const isDark = theme === "dark"
root.classList.remove(isDark ? "light" : "dark")
root.classList.add(theme)
localStorage.setItem("color-theme", theme)
}
if (initialTheme) {
rawSetTheme(initialTheme)
}
React.useEffect(
_ => {
rawSetTheme(theme)
},
[theme]
)
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
)
}