Skip to content

Instantly share code, notes, and snippets.

@fakkio
Last active July 5, 2023 22:10
Show Gist options
  • Save fakkio/2aa3da4f964d62106bae84bd1a67eb59 to your computer and use it in GitHub Desktop.
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)
// 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;
import React from "react";
import useDarkTheme from "./useDarkTheme";
const Component = () => {
const isDark = useDarkTheme();
return <div>Dark mode: {isDark ? "on" : "off"}</div>;
};
export default Component;
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