Created
June 19, 2021 00:02
-
-
Save vzhou842/79a32c08c5ba904fe21cc5f4484800b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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