Skip to content

Instantly share code, notes, and snippets.

@popeating
Last active March 31, 2021 13:24
Embed
What would you like to do?
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