Skip to content

Commit

Permalink
Update initial theme application
Browse files Browse the repository at this point in the history
  • Loading branch information
HamishMW committed May 7, 2022
1 parent 940f49a commit 3c27f48
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 4 deletions.
6 changes: 4 additions & 2 deletions src/components/ThemeProvider/ThemeProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import GothamBookItalic from 'assets/fonts/gotham-book-italic.woff2';
import GothamBook from 'assets/fonts/gotham-book.woff2';
import GothamMediumItalic from 'assets/fonts/gotham-medium-italic.woff2';
import GothamMedium from 'assets/fonts/gotham-medium.woff2';
import { useHasMounted } from 'hooks';
import Head from 'next/head';
import { createContext, useEffect } from 'react';
import { classes, media } from 'utils/style';
Expand All @@ -23,14 +24,15 @@ export const ThemeProvider = ({
const currentTheme = { ...theme[themeId], ...themeOverrides };
const parentTheme = useTheme();
const isRootProvider = !parentTheme.themeId;
const hasMounted = useHasMounted();

// Save root theme id to localstorage and apply class to body
useEffect(() => {
if (isRootProvider) {
if (isRootProvider && hasMounted) {
window.localStorage.setItem('theme', JSON.stringify(themeId));
document.body.dataset.theme = themeId;
}
}, [themeId, isRootProvider]);
}, [themeId, isRootProvider, hasMounted]);

return (
<ThemeContext.Provider value={currentTheme}>
Expand Down
1 change: 0 additions & 1 deletion src/layouts/App/reducer.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export const initialState = {
menuOpen: false,
theme: 'dark',
};

export function reducer(state, action) {
Expand Down
5 changes: 4 additions & 1 deletion src/pages/_document.page.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ export default function Document() {
<body data-theme="dark" tabIndex={-1}>
<script
dangerouslySetInnerHTML={{
__html: `document.body.dataset.theme = JSON.parse(localStorage.getItem('theme')) || 'dark';`,
__html: `
const initialTheme = JSON.parse(localStorage.getItem('theme'));
document.body.dataset.theme = initialTheme || 'dark';
`,
}}
/>
<Main />
Expand Down

0 comments on commit 3c27f48

Please sign in to comment.