react-native-flexboxreact-native-stylesheet

Overriding a Single Style Prop from Stylesheet Using React Native


With React Native, I'm looking to use StyleSheet to define a style and then use that style in numerous components, but I would like to change or override individual props for a few components. For example, a stack of 10 views with 5 different colors but all other props the same. Is this possible? What does the syntax look like?

I can't imagine I have to define 5 different styles or use in-line styling. Thanks very much for your help.


Solution

  • You can export some globally used styles from a single module, and import them wherever you need. Then to combine styles you can use the array syntax like [ styleA, styleB ].

    So in a simple example you could do something like:

    // ./styles.js
    
    import { StyleSheet } from 'react-native';
    
    export default StyleSheet.create({
      containerDefault: {
        height: 100,
        width: 300,
        backgroundColor: 'black'
      },
      backgroundBlue: {
        backgroundColor: 'blue'
      },
      backgroundGreen: {
        backgroundColor: 'green'
      }
    });
    

    And then...

    // ./SomeComponent.js
    
    import React from 'react';
    import { View, Text } from 'react-native';
    import styles from './styles';
    
    const ComponentBlack = () => {
      return (
        <View style={styles.containerDefault}>
          <Text>I should be black</Text>
        </View>
      );
    };
    
    const ComponentBlue = () => {
      return (
        <View style={[styles.containerDefault, styles.backgroundBlue]}>
          <Text>I should be blue</Text>
        </View>
      );
    };
    
    const ComponentGreen = () => {
      return (
        <View style={[styles.containerDefault, styles.backgroundGreen]}>
          <Text>I should be green</Text>
        </View>
      );
    };
    
    export default () => {
      return (
        <View>
          <ComponentBlack />
          <ComponentBlue />
          <ComponentGreen />
        </View>
      );
    };