Created
May 7, 2024 09:07
-
-
Save wvteijlingen/593bff50a72ff90aeee11bad1b207b00 to your computer and use it in GitHub Desktop.
React Native Dark Mode
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 useThemedStyles, { createThemedStyleSheet } from "./useThemedStyles" | |
export default function Component() { | |
const [styles, colorScheme] = useThemedStyles(stylesheet) | |
// ... | |
} | |
const stylesheet = createThemedStyleSheet((theme) => ({ | |
container: { | |
backgroundColor: theme.colors.background | |
} | |
}) |
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
export const lightMode = { | |
colors: lightModeColors, | |
spacing, | |
borderRadius, | |
typography, | |
} | |
export const darkMode = { | |
colors: darkModeColors, | |
spacing, | |
borderRadius, | |
typography, | |
} | |
export type Theme = typeof lightMode |
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 { useMemo } from "react" | |
import { ColorSchemeName, ImageStyle, StyleSheet, TextStyle, ViewStyle, useColorScheme } from "react-native" | |
import { Theme, darkMode, lightMode } from "./themes" | |
type NamedStyles<T> = { [P in keyof T]: ViewStyle | TextStyle | ImageStyle } | |
export default function useThemedStyles<T extends NamedStyles<T> | NamedStyles<any>>( | |
sheetBuilder: (theme: Theme, colorScheme: ColorSchemeName) => T | |
): [T, Theme] { | |
const colorScheme = useColorScheme() | |
const theme: Theme = colorScheme === "dark" ? darkMode : lightMode | |
const sheet = useMemo(() => sheetBuilder(theme, colorScheme), [theme]) | |
return [sheet, theme] | |
} | |
export function createThemedStyleSheet<T extends NamedStyles<T> | NamedStyles<any>>( | |
builder: (theme: Theme, colorScheme: ColorSchemeName) => T | |
): (theme: Theme, colorScheme: ColorSchemeName) => T { | |
return (theme: Theme, colorScheme: ColorSchemeName) => { | |
return StyleSheet.create(builder(theme, colorScheme)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment