Skip to content

Instantly share code, notes, and snippets.

@wvteijlingen
Created May 7, 2024 09:07
Show Gist options
  • Save wvteijlingen/593bff50a72ff90aeee11bad1b207b00 to your computer and use it in GitHub Desktop.
Save wvteijlingen/593bff50a72ff90aeee11bad1b207b00 to your computer and use it in GitHub Desktop.
React Native Dark Mode
import useThemedStyles, { createThemedStyleSheet } from "./useThemedStyles"
export default function Component() {
const [styles, colorScheme] = useThemedStyles(stylesheet)
// ...
}
const stylesheet = createThemedStyleSheet((theme) => ({
container: {
backgroundColor: theme.colors.background
}
})
export const lightMode = {
colors: lightModeColors,
spacing,
borderRadius,
typography,
}
export const darkMode = {
colors: darkModeColors,
spacing,
borderRadius,
typography,
}
export type Theme = typeof lightMode
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