Combining multiple styles in React Native
Nick Janssen
Posted on October 8th 2019
When styling your web application or website in React, you can pass a style object to your JSX, like so:
const styles = {
  square: {
    backgroundColor: "blue",
    width: 100,
    height: 100    
  }
};

const SquareDiv = () => <div style={styles.square} />
In React Native, you would write the following:
const styles = StyleSheet.create({
  square: {
    backgroundColor: "blue",
    width: 100,
    height: 100    
  }
});

const SquareView = () => <View style={styles.square} />
Tip

You don't absolutely have to specify Stylesheet.create() in React Native.

Regular objects will work as well but have a performance impact.

Now, suppose you'd like to have a rounded variant with the same color and dimensions. Let's create another style called round.
  round: {
    borderRadius: 10
  }
In regular React, you will have to use Object.assign() or the spread operator to combine two styles.
const styles = {
  square: {
    backgroundColor: "blue",
    width: 100,
    height: 100    
  },
  round: {
    borderRadius: 10
  }  
};

const RoundDiv = () => <div 
  style={Object.assign({}, styles.square, styles.round)} />
// or
const RoundDiv = () => <div 
  style={{...styles.square, ...styles.round}} />  
In React Native, there's a third and better way to combine styles. Use the array operator.
const styles = StyleSheet.create({
  square: {
    background: "blue",
    width: 100,
    height: 100    
  },
  round: {
    borderRadius: 10
  }  
});

const RoundView = () => <View style={[styles.square, styles.round]} />  
Caution
This will not work in regular React.
If you write exclusively for React Native, it makes sense to use the array operator. However, if you are reusing components in a web project using regular React, it probably makes more sense to use Object.assign or the spread operator.
Nick Janssen
Built with StyledPage