Created
April 9, 2024 05:17
-
-
Save drazulay/bec1722850998cedac6007284413887b to your computer and use it in GitHub Desktop.
Toggle between light and dark color modes with React
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, { useEffect, useState } from "react"; | |
import { useMediaQuery } from "react-responsive"; | |
export const DarkModeToggle = () => { | |
const [isDark, setIsDark] = useState(true); | |
useMediaQuery( | |
{ | |
query: "(prefers-color-scheme: dark)", | |
}, | |
undefined, | |
(isSystemDark) => setIsDark(isSystemDark) | |
); | |
useEffect(() => { | |
if (isDark) { | |
document.body.classList.add('dark'); | |
} else { | |
document.body.classList.remove('dark'); | |
} | |
}, [isDark]); | |
return ( | |
<p className="dark-mode-toggle" aria-label="Dark mode toggle" onClick={() => {setIsDark(!isDark)}}> | |
<span className="dark-mode-toggle-text font-size-small font-weight-light">Theme:</span><span className="dark-mode-toggle-img" role="img" aria-label="Sun or moon emoji">{ isDark ? "🌙" : "🔆"}</span> | |
</p> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment