Skip to content

Instantly share code, notes, and snippets.

@ricexen
Last active December 17, 2019 23:48
Show Gist options
  • Save ricexen/d3b0c072f44398c218d820a32d847966 to your computer and use it in GitHub Desktop.
Save ricexen/d3b0c072f44398c218d820a32d847966 to your computer and use it in GitHub Desktop.
React Native - Spread styles

The purpose of this gist is to explain how to have a better code style writing. And I think that the right way is to have only way to access to the style code. In case that you don't need to pass properties with styles to your component.

If you have something like this

render() {
  return (
    <View style={[styles.cardContainer, { backgroundColor: colorStyle.background }]}>
      <View style={[styles.iconContainer, { backgroundColor: colorStyle.icon }]}>
        <Icon {...blablaProperties} />
      </View>
    </View>
  );
}

You can see that in the style you can see objects with style in the code.

<View style={[styles.cardContainer, { backgroundColor: colorStyle.background }]}>
  <View style={[styles.iconContainer, { backgroundColor: colorStyle.icon }]}>
    <Icon {...blablaProperties} />
  </View>
</View>

In order to keep the code clean you can avoid that spreading the properties of that style object in the another one, resulting in a new one with all the properties of the first one and adding another property to the new one. Like so:

const stylesOfThisRender = StylesSheet.create<StylesInterface>({
   newCardContainerStyle: {
     ...styles.cardContainer,
     backgroundColor: colorStyle.background,
   },
   newIconContainerStyle: {
     ...styles.iconContainer,
     backgroundColor: colorStyle.icon,
   }
});

And the resulting render whould be something like this

<View style={styles.newCardContainerStyle}>
  <View style={styles.newIconContainerStyle}>
    <Icon {...blablaProperties} />
  </View>
</View>

All of this is to have reusable style code and have less repeated code

NOTE: It could cause perform issues if you write multiple spreads around the final style but if is that the case you should refactor your style code it could be simpler than yout think ;P

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment