Skip to content

Instantly share code, notes, and snippets.

View vzhou842's full-sized avatar

Victor Zhou vzhou842

View GitHub Profile
// ...
const darkQuery = window.matchMedia('(prefers-color-scheme: dark)');
// Your Toggle component will need to register here to get updates.
window.__themeListeners = [];
darkQuery.addListener(e => {
window.__setPreferredTheme(e.matches ? 'dark' : 'light');
window.__themeListeners.forEach(l => l());
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
// code here
// ...
})();
`.replace(/\n/g, ' ').replace(/ {2}/g, ''),
}} />
import React, { useCallback, useState } from 'react';
import Toggle from 'react-toggle';
const DarkModeToggle = () => {
if (typeof window === 'undefined') {
// Never server-side render this, since we can't determine
// the correct initial state until we get to the client.
// Alternatively, use a loading placeholder here.
return null;
}
// This is the code we're inserting at the top of our page
// ...
// Update the current theme to either 'light' or 'dark'
function setTheme(theme) {
window.__theme = theme;
console.log('Theme updated:', theme);
if (theme === 'dark') {
/* Light Mode */
:root {
--color-background: white;
--color-text: #222;
--color-primary: #164BC5;
/* ... more colors */
}
/* Dark Mode */
:root.dark {
// This is the code we're inserting at the top of our page
(function() {
// Update the current theme to either 'light' or 'dark'
function setTheme(theme) {
window.__theme = theme;
// TODO: do other logic to update theme here
console.log('Theme updated:', theme);
};
const React = require('react');
exports.onRenderBody = ({ setHeadComponents }) => {
setHeadComponents([
<script
dangerouslySetInnerHTML={{
__html: '// REPLACE THIS WITH ACTUAL CODE',
}}
/>,
]);
@vzhou842
vzhou842 / os-preference.js
Created June 18, 2021 23:56
OS Preference
const darkQuery = window.matchMedia('(prefers-color-scheme: dark)');
if (darkQuery.matches) {
console.log('The user prefers dark mode!');
}
darkQuery.addListener(e => {
console.log(`Preference update: ${e.matches ? 'does' : 'does not'} prefer dark mode`);
});
@vzhou842
vzhou842 / saved-theme-preference.js
Last active June 18, 2021 23:56
Saved Theme Preference
// Save this at some point
localStorage.setItem('preferred-theme', 'dark');
// User can close the tab, quit the browser, etc...
// Come back later and this will still be set
const theme = localStorage.getItem('preferred-theme');
<p>
Unfortunately, no results were found for{' '}
<span dangerouslySetInnerHTML={{ __html: query }} />.
</p>