-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgatsby-ssr.js
More file actions
45 lines (36 loc) · 1.62 KB
/
Copy pathgatsby-ssr.js
File metadata and controls
45 lines (36 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const React = require('react');
// https://victorzhou.com/blog/dark-mode-gatsby/
exports.onRenderBody = ({ setHeadComponents }) => {
setHeadComponents([
<script
dangerouslySetInnerHTML={{
__html: `(function() {
function setTheme(theme) {
window.__theme = theme;
console.log('Theme updated:', theme);
if (theme === 'dark') {
document.documentElement.className = 'dark';
} else {
document.documentElement.className = '';
}
};
window.__setPreferredTheme = function(theme) {
setTheme(theme);
try {
localStorage.setItem('preferred-theme', theme);
} catch (e) {}
};
let preferredTheme;
try {
preferredTheme = localStorage.getItem('preferred-theme');
} catch (e) {}
let darkQuery = window.matchMedia('(prefers-color-scheme: dark)');
darkQuery.addListener(e => {
window.__setPreferredTheme(e.matches ? 'dark' : 'light');
});
setTheme(preferredTheme || (darkQuery.matches ? 'dark' : 'light'));
})();`.replace(/\n/g, ' ').replace(/ {2}/g, ''),
}}
/>
]);
};