Search code examples
react-nativereact-native-stylesheet

How to reuse a style into same StyleSheet


I am using React Native, and I want to reuse a style within the same StyleSheet. My styles are as follows:

buttonContained: {
        borderRadius: 8,
        backgroundColor: Colors.primary,
        padding: 15,
        height: 48,
        alignItems: 'center',
        justifyContent: 'center',
    },
    buttonOutlined: {
        padding: 15,
        borderRadius: 8,
        height: 48,
        borderColor: Colors.primary,
        borderWidth: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },

However, I've noticed that these two buttons share the same styles, and similar styles will be used for others that I'll create. I want to reuse styles because if the default style changes, I only need to modify it in one place.

Here's an example of what I want to do:

export const globalStyles = StyleSheet.create({
      buttonDefault: {
        borderRadius: 8,
        padding: 15,
        height: 48,
        alignItems: 'center',
        justifyContent: 'center',
    },
    buttonContained: {
        **(reuse defaultStyle here)**
        backgroundColor: Colors.primary,
    },
    buttonOutlined: {
        **(reuse defaultStyle here)**
        borderColor: Colors.primary,
        borderWidth: 1,
    },
})

Does anyone know how to accomplish this?"


Solution

  • Put reusable styles to one style sheet and then use that wherever needed. Something like this:

    const defaultStyles = StyleSheet.create({
      buttonDefault: {
        borderRadius: 8,
        padding: 15,
        height: 48,
        alignItems: 'center',
        justifyContent: 'center',
      }
    });
    
    export const globalStyles = StyleSheet.create({
      buttonDefault: {
        ...defaultStyles.buttonDefault
      },
      buttonContained: {
        ...defaultStyles.buttonDefault,
        backgroundColor: Colors.primary,
      },
      buttonOutlined: {
        ...defaultStyles.buttonDefault,
        borderColor: Colors.primary,
        borderWidth: 1,
      },
    });