Skip to content

Instantly share code, notes, and snippets.

@popeating
Last active March 31, 2021 13:24
Show Gist options
  • Save popeating/1be6d4fe461d33fb28b2e2ec58b0a126 to your computer and use it in GitHub Desktop.
Save popeating/1be6d4fe461d33fb28b2e2ec58b0a126 to your computer and use it in GitHub Desktop.
const React = require('react');
exports.onRenderBody = ({ setHeadComponents }) => {
setHeadComponents([
<script
key="darkmode"
dangerouslySetInnerHTML={{
__html: `(function() {
function setTheme(theme) {
window.__theme = theme;
if (theme === 'dark') {
document.documentElement.className = 'dark';
} else {
document.documentElement.className = '';
}
};
window.__setPreferredTheme = function(theme) {
setTheme(theme);
try {
localStorage.setItem('color-theme', theme);
} catch (e) {}
};
let preferredTheme;
try {
preferredTheme = localStorage.getItem('color-theme');
} catch (e) {}
let darkQuery = window.matchMedia('(prefers-color-scheme: dark)');
setTheme(preferredTheme || (darkQuery.matches ? 'dark' : 'light'));
})();`,
}}
/>,
]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment