Skip to content

Instantly share code, notes, and snippets.

@vzhou842
Created June 19, 2021 00:02
Show Gist options
  • Save vzhou842/79a32c08c5ba904fe21cc5f4484800b3 to your computer and use it in GitHub Desktop.
Save vzhou842/79a32c08c5ba904fe21cc5f4484800b3 to your computer and use it in GitHub Desktop.
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;
}
const [checked, setChecked] = useState(window.__theme === 'dark');
const onChange = useCallback(
e => {
const isChecked = e.target.checked;
setChecked(isChecked);
window.__setPreferredTheme(isChecked ? 'dark' : 'light');
},
[setChecked]
);
return <Toggle checked={checked} onChange={onChange} />;
};
export default DarkModeToggle;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment