mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2025-12-25 02:14:11 -05:00
fix(client): initialize theme during gatsby SSR (#61922)
This commit is contained in:
@@ -8,7 +8,11 @@ import i18n from './i18n/config';
|
||||
import { stripe } from './src/utils/stripe';
|
||||
import { createStore } from './src/redux/create-store';
|
||||
import layoutSelector from './utils/gatsby/layout-selector';
|
||||
import { getheadTagComponents, getPostBodyComponents } from './utils/tags';
|
||||
import {
|
||||
getheadTagComponents,
|
||||
getPostBodyComponents,
|
||||
getPreBodyThemeScript
|
||||
} from './utils/tags';
|
||||
import GrowthBookProvider from './src/components/growth-book/growth-book-wrapper';
|
||||
|
||||
const store = createStore();
|
||||
@@ -34,9 +38,11 @@ export const wrapPageElement = layoutSelector;
|
||||
export const onRenderBody = ({
|
||||
pathname,
|
||||
setHeadComponents,
|
||||
setPreBodyComponents,
|
||||
setPostBodyComponents
|
||||
}) => {
|
||||
setHeadComponents(getheadTagComponents());
|
||||
setPreBodyComponents(getPreBodyThemeScript());
|
||||
setPostBodyComponents(getPostBodyComponents(pathname));
|
||||
};
|
||||
|
||||
|
||||
@@ -62,3 +62,36 @@ export function getPostBodyComponents(superblock: string): JSX.Element[] {
|
||||
|
||||
return scripts.filter(Boolean);
|
||||
}
|
||||
|
||||
export function getPreBodyThemeScript(): JSX.Element[] {
|
||||
const script = (
|
||||
<script
|
||||
key='prebody-theme-init'
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `
|
||||
(function(){
|
||||
let theme = 'light';
|
||||
const localTheme = localStorage.getItem('theme');
|
||||
|
||||
if (localTheme !== null) {
|
||||
theme = localTheme === 'dark' ? 'dark' : 'light';
|
||||
} else if (
|
||||
window.matchMedia &&
|
||||
window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
) {
|
||||
theme = 'dark';
|
||||
}
|
||||
|
||||
const bodyEl = document && document.body;
|
||||
|
||||
if (bodyEl && bodyEl.classList) {
|
||||
bodyEl.classList.remove('light-palette');
|
||||
bodyEl.classList.remove('dark-palette');
|
||||
bodyEl.classList.add(theme + '-palette');
|
||||
}
|
||||
})();`
|
||||
}}
|
||||
/>
|
||||
);
|
||||
return [script];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user