Skip to content

Commit

Permalink
fix: hopefully fix for the-programmers-hangout#334
Browse files Browse the repository at this point in the history
  • Loading branch information
SagnikPradhan committed Oct 1, 2021
1 parent 70762f0 commit eef5d17
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
34 changes: 28 additions & 6 deletions gatsby-ssr.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
/**
* Implement Gatsby's SSR (Server Side Rendering) APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/ssr-apis/
*/
import React from "react"

// You can delete this file if you're not using it
const ThemeScript = () => {
const themeScript = `
(function() {
function getInitialTheme() {
const userSetTheme = window.localStorage.getItem("theme")
const prefersLightTheme = window.matchMedia(
"(prefers-color-scheme: light)"
)
if (userSetTheme && userSetTheme !== '"unset"') return userSetTheme
else if (prefersLightTheme.matches === true) return "light"
else return "dark"
}
document.documentElement.style.setProperty(
"--initial-theme",
getInitialTheme()
)
})()
`

return <script dangerouslySetInnerHTML={{ __html: themeScript }} />
}

export const onRenderBody = ({ setPreBodyComponents }) => {
setPreBodyComponents(<ThemeScript></ThemeScript>)
}
6 changes: 3 additions & 3 deletions src/ThemeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ const ThemeProvider: FC<IScopedDownChildren> = ({ children }) => {

// App's current theme
const [theme, setTheme] = useState<ThemeType>(
localTheme === "unset" ? "dark" : localTheme
document.documentElement.style.getPropertyValue(
"--initial-theme"
) as ThemeType
)

const themeObject = useMemo(
Expand All @@ -40,8 +42,6 @@ const ThemeProvider: FC<IScopedDownChildren> = ({ children }) => {
"(prefers-color-scheme: light)"
)

setTheme(prefersLightTheme.matches ? "light" : "dark")

prefersLightTheme.onchange = ({ matches }) =>
setTheme(matches ? "light" : "dark")

Expand Down

0 comments on commit eef5d17

Please sign in to comment.