Last active
February 15, 2021 01:41
-
-
Save ChronSyn/c8fd59dcf99c5018e5b4209c00f99985 to your computer and use it in GitHub Desktop.
React Native - useTheme hook
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 { ITheme } from "@Themes/interfaces"; | |
import { DarkTheme } from "@Themes/theme.dark"; | |
import { LightTheme } from "@Themes/theme.light"; | |
import React from "react"; | |
import { useColorScheme } from "react-native-appearance"; | |
export const useTheme = (): [ITheme] => { | |
const scheme = useColorScheme(); | |
const [currentTheme, setCurrentTheme] = React.useState<ITheme>(DarkTheme); | |
React.useEffect(() => { | |
setCurrentTheme(scheme === "dark" ? DarkTheme : LightTheme); | |
}, [scheme]); | |
return [currentTheme]; | |
}; |
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
/** | |
* This version allows you to override the theme by passing a theme as a parameter to the hook | |
*/ | |
import { ITheme } from "@Themes/interfaces"; | |
import { DarkTheme } from "@Themes/theme.dark"; | |
import { LightTheme } from "@Themes/theme.light"; | |
import React from "react"; | |
import { useColorScheme } from "react-native-appearance"; | |
export const useTheme = (forceTheme?: ITheme): [ITheme] => { | |
const scheme = useColorScheme(); | |
const [currentTheme, setCurrentTheme] = React.useState<ITheme>(forceTheme ?? DarkTheme); | |
React.useEffect(() => { | |
if (forceTheme){ | |
setCurrentTheme(forceTheme); | |
} else { | |
setCurrentTheme(scheme === "dark" ? DarkTheme : LightTheme); | |
} | |
}, [scheme, forceTheme]); | |
return [currentTheme]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment