Last active
July 5, 2023 22:10
-
-
Save fakkio/2aa3da4f964d62106bae84bd1a67eb59 to your computer and use it in GitHub Desktop.
A simple hook for ionic react to read if dark theme is on or off. Works on browser and mobile (> ios13 || > android9)
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
// Other imports | |
import useDarkTheme from "./useDarkTheme"; | |
const App: React.FC = () => { | |
const toggleDarkTheme = (shouldAdd: boolean) => { | |
document.body.classList.toggle("dark", shouldAdd); | |
}; | |
const isDark = useDarkTheme(); | |
useEffect(() => { | |
toggleDarkTheme(isDark); | |
}, [isDark]); | |
return ( | |
<IonApp> | |
// Ion app stuff | |
</IonApp> | |
); | |
}; | |
export default App; |
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 from "react"; | |
import useDarkTheme from "./useDarkTheme"; | |
const Component = () => { | |
const isDark = useDarkTheme(); | |
return <div>Dark mode: {isDark ? "on" : "off"}</div>; | |
}; | |
export default Component; |
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 { | |
ThemeDetection, | |
ThemeDetectionResponse, | |
} from "@ionic-native/theme-detection"; | |
import {useState} from "react"; | |
const useDarkTheme = () => { | |
const [isDark, setIsDark] = useState( | |
window.matchMedia("(prefers-color-scheme: dark)").matches | |
); | |
ThemeDetection.isAvailable() | |
.then((res: ThemeDetectionResponse) => { | |
if (res.value) { | |
ThemeDetection.isDarkModeEnabled() | |
.then((res: ThemeDetectionResponse) => { | |
setIsDark(res.value); | |
}) | |
.catch((error: any) => console.error(error)); | |
} | |
}) | |
.catch((error: any) => { | |
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)"); | |
prefersDark.addEventListener("change", (mediaQuery) => { | |
setIsDark(mediaQuery.matches); | |
}); | |
}); | |
return isDark; | |
}; | |
export default useDarkTheme; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment