Skip to content

Instantly share code, notes, and snippets.

@sillyslux
Last active October 9, 2019 12:24
Show Gist options
  • Save sillyslux/b76f25618d77284db50e3297e55d7901 to your computer and use it in GitHub Desktop.
Save sillyslux/b76f25618d77284db50e3297e55d7901 to your computer and use it in GitHub Desktop.
win/mac/linux theme change listener for react
import React from 'react';
import { themeChange } from '../../../style/theme';
...
themeChange.subscribe(console.log); // logs dark/light
/* theme file for react-jss */
const theme = {};
const themeChange = {
listeners: [],
subscribe: cb => themeChange.listeners.push(cb)
}
const isDark = window.matchMedia('(prefers-color-scheme: dark)');
isDark.addListener(evt=>{
if(evt.matches) theme.colorPrimary = 'yellow';
else theme.colorPrimary = 'red';
themeChange.listeners.forEach(handler => handler(evt.matches?'dark':'light'))
});
if(isDark.matches) theme.colorPrimary = 'yellow';
else theme.colorPrimary = 'red';
export { theme as default, themeChange }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment