The problem
Applying styles using object spread works on Android and iOS but the styles do not get applied when rendering on the web.
Creating a style object like this
<View
style={{
...styles.bar,
}}
/>
The styles.bar do not get applied to the object when rendered on the web.
How to reproduce
Simplified test case: https://codesandbox.io/s/43lv9oq1j9
Steps to reproduce:
bar: {
height: 56,
width: 200,
backgroundColor: "blue"
}
<View
style={{
...styles.bar,
}}
/>
<View /> does not have the styles.Expected behavior
I'd expect the object spread values to be applied to the view in the same way it does on iOS and Android.
Environment (include versions). Did this work in previous versions?
If I refactor styles to use array syntax then it does work on all platforms
<View
style={[styles.bar]}
/>
However I prefer object spread syntax because it makes declaring dynamic properties cleaner in my opinion
<View
style={{
...styles.bar,
backgroundColor: this.state.dynamicColor
}}
/>
vs
<View
style={[
styles.bar,
{backgroundColor: this.state.dynamicColor},
]}
/>
The spread syntax is not supported with StyleSheet.create. It's only very recently that React Native made an internal change that allows this use to occur as a side-effect. But you should avoid creating new objects like this in the render method, as it is bad for performance. Instead, continue using the array syntax to combine styles.
Most helpful comment
The spread syntax is not supported with
StyleSheet.create. It's only very recently that React Native made an internal change that allows this use to occur as a side-effect. But you should avoid creating new objects like this in the render method, as it is bad for performance. Instead, continue using the array syntax to combine styles.