Skip to content

Instantly share code, notes, and snippets.

@nmquebb
Last active December 1, 2021 01:57
Show Gist options
  • Select an option

  • Save nmquebb/1d5312476282e7a6c543e8d745a9b4ab to your computer and use it in GitHub Desktop.

Select an option

Save nmquebb/1d5312476282e7a6c543e8d745a9b4ab to your computer and use it in GitHub Desktop.
React Native light/dark theme styles
export const styles = {
base: StyleSheet.create({
button: { padding: 20 },
}),
light: StyleSheet.create({
button: { background: 'blue', color: 'white' },
}),
dark: StyleSheet.create({
button: { background: 'white', color: 'blue' },
}),
};
import { useThemeStyles } from './use-theme-styles'
export const Button = () => {
const s = useThemeStyles(styles);
return (
<TouchableOpacity style={s.button}>
<Text>Submit</Text>
</TouchableOpacity>
);
};
import React, { useMemo } from 'react';
import { StyleProp, StyleSheet, useColorScheme } from 'react-native';
type ThemeKeys = 'base' | 'light' | 'dark';
type ComposedStyles = StyleProp<object>;
type StylesRecord = Record<ThemeKeys, ComposedStyles>;
export function useThemeStyles<T extends StylesRecord>(styles: T): T['base'] {
const theme = useColorScheme() ?? 'light';
return useMemo(() => {
return StyleSheet.compose(styles.base, styles[theme]);
}, [theme]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment