Consider StyleSheet.flatten
Currently glamorous components will become configured through a collection of styles. In this issue, we'll explore flattening the collection of styles into a single style object with StyleSheet.flatten.
Currently glamorous components will contain an array of styles, for example:
const staticStyles = StyleSheet.create({
styleOne: {margin: 10}
})
const GlamorousView = glamorous.view(
// stylesheet styles
staticStyles.styleOne,
// inline styles
{padding: 10},
// dynamic styles
(props) => ({
width: props.big ? 200 : 100,
height: props.big ? 200 : 100
}),
(props, theme) => ({
backgroundColor: theme.primaryColor
})
)
<GlamorousView style={{margin: 5, padding: 5}} />
Results in
<GlamorousView
big
theme={{primaryColor: 'red'}}
style={[
staticStyles.styleOne, // this would actually be a StyleSheet UID
{padding: 10}, // this would actually be a StyleSheet UID
{width: 200, height: 200},
{backgroundColor: 'red'},
{margin: 5, padding: 5}
]}
/>
With StyleSheet.flatten, this would merge them into a single style object:
<GlamorousView
big
theme={{primaryColor: 'red'}}
style={{
padding: 5,
margin: 5,
width: 200,
height: 200,
backgroundColor: 'red'
}}
/>
Caveats
When using StyleSheet.create, it creates a registration for the style which is simply a unique ID. This is used to avoid the same style being communicated over the bridge to the native side when it hasn't changed.
For example
cont style = StyleSheet.create({
foo: {color: 'red'}
})
console.log(style.foo) // 1
By using StyleSheet.flatten, we no longer get the performance advantage from registered styles.
However, we're passing an array of styles at the end of the day, and if there are dynamic styles, or style-attributes (backgroundColor={1}), then those will be style objects either way and won't go through the registration process.
Verification
In order to determine the proper implementation it would be helpful to know
- A better understanding of cached styles being passed in arrays with inline styles
- The performance impact between the two