skip to Main Content

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?"

2

Answers


  1. You can achieve what you want but in a different way, have you tried this?

    <ButtonOne style={[styles.buttonDefault, styles.buttonContained]} />
    
    <ButtonTwo style={[styles.buttonDefault, styles.buttonOutlined]} />
    

    or this:

    export const globalStyles = StyleSheet.create({
        buttonDefault: {
            borderRadius: 8,
            padding: 15,
            height: 48,
            alignItems: 'center',
            justifyContent: 'center',
        },
        buttonContained: {
            ...globalStyles.buttonDefault,
            backgroundColor: Colors.primary,
        },
        buttonOutlined: {
            ...globalStyles.buttonDefault,
            borderColor: Colors.primary,
            borderWidth: 1,
        },
    });
    
    Login or Signup to reply.
  2. 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,
      },
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search