Skip to content

Instantly share code, notes, and snippets.

@rickyalmeidadev
Last active December 25, 2021 01:48
Show Gist options
  • Save rickyalmeidadev/1f666140adb6c5fe7926c94eec07c987 to your computer and use it in GitHub Desktop.
Save rickyalmeidadev/1f666140adb6c5fe7926c94eec07c987 to your computer and use it in GitHub Desktop.
Reactive styles based on user’s color scheme in React Native
import makeStyles from '@app/helpers/make-styles'
const useStyles = makeStyles(theme => ({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: theme.bg,
},
text: {
color: theme.ink,
},
}))
export default useStyles
import React from 'react'
import {Text, View} from 'react-native'
import useStyles from './App.styles'
const App = () => {
const styles = useStyles()
return (
<View style={styles.container}>
<Text style={styles.text}>{JSON.stringify({styles}, null, 2)}</Text>
</View>
)
}
export default App
const dark = {
bg: 'black',
ink: 'white',
}
export default dark
const light = {
bg: 'white',
ink: 'black',
}
export default light
import {ImageStyle, StyleProp, TextStyle, ViewStyle} from 'react-native'
import useTheme from '@app/hooks/use-theme'
type Styles = {[key: string]: StyleProp<ImageStyle | TextStyle | ViewStyle>}
type Theme = ReturnType<typeof useTheme>
type Factory<T extends Styles> = (theme: Theme) => T
const makeStyles = <T extends Styles>(factory: Factory<T>) => () => {
const theme = useTheme()
return factory(theme)
}
export default makeStyles
import {useColorScheme} from 'react-native'
import dark from '@app/theme/dark'
import light from '@app/theme/light'
const useTheme = () => {
const colorScheme = useColorScheme()
return colorScheme === 'dark' ? dark : light
}
export default useTheme
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment