If you use a dynamic function, library will wrap it in a Proxy to make sure the correct values of breakpoints will be used:
conststylesheet=createStyleSheet(theme=> ({
scrollContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
post: (index:number) => ({
// breakpoints and media queries works with dynamic function
backgroundColor: {
xs: index %2===0
? theme.colors.gold
: theme.colors.silver,
sm: theme.colors.red
}
})
}))
Dynamic themes
You can incorporate as many themes as you desire in your application. While there’s flexibility in how you structure your theme, it’s essential to maintain consistency with the TypeScript type:
To promote reusability and maintainability, it’s a good practice to share as many values between themes as possible:
// move shared colors to object
constsharedColors= {
barbie: '#ff9ff3',
oak: '#1dd1a1',
sky: '#48dbfb',
fog: '#c8d6e5',
aloes: '#00d2d3'
}
exportconstlightTheme= {
colors: {
// reuse or override them
...sharedColors,
backgroundColor: '#ffffff',
typography: '#000000'
}
// other keys in common with darkTheme
}
exportconstdarkTheme= {
colors: {
// reuse or override them
...sharedColors,
backgroundColor: '#000000',
typography: '#ffffff'
}
// other keys in common with lightTheme
}
// export type that will be used to describe your theme
// switching theme will re-render your stylesheets automatically
return (
<UnistylesThemetheme={yourAppTheme}>
<Examples.Extreme />
</UnistylesTheme>
)
}
Media Queries
For more advanced usage and pixel perfect designs you can also use a custom media queries. Library supports 4 types of media queries (w-width, h-height):
:w[200, 500] -with upper and lower bounds, it translates to width from 200-500px
:w[, 800] -with upper bound only, it's equal to width from 0-800px
:h[400] - lower bound only, it means height from 400px
:h[200, 300]:w[500] - combined queries for both width and height
Media queries can be mixed with breakpoints, but have a bigger priority:
conststylesheet=createStyleSheet(theme=> ({
container: {
justifyContent: 'center',
alignItems: 'center',
flexDirection: {
xs: 'column',
sm: 'row',
},
backgroundColor: {
md: theme.colors.background,
// even though md might overlap with >600px, lib will use 'barbie'
':w[600]': theme.colors.barbie
}
},
text: {
color: theme.colors.typography
}
}))
Variants
react-native-unistyles isn’t a UI/component library, so you’re in charge of designing variants. With no restrictions and using your creativity, you can easily create variants for your components.
Let’s examine variants for the Text component. Imagine you want to create several variants for your Typography components:
Remember, that if you want to spread styles like so you need to export your theme “as const” for TypeScript.
This is how React Native types works, and you can see the same behavior with StyleSheet.create.