Search code examples
react-nativereact-native-stylesheet

Object in StyleSheet in React Native


I'd like to know if there is something like what can be done in .less with StyleSheet object in React Native to group some objects.

For example if I render something like this :

<View style={styles.wrapper}>
   <View style={styles.wrapper.left}></View>
   <View style={styles.wrapper.right}></View>
</View>

and have a stylesheet object like this :

const styles = StyleSheet.create({
  wrapper: {
    /* Some properties */,
    left: {
      /* Some properties */,
    },
    right: {
      /* Some properties */,
    },
  }
})

Thanks !


Solution

  • You can use getter for this purpose

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

    you can use this with StyleSheet.create

    let style = {
      wrapper: {
        color: "red",
        position: "absolute",
      },
      
      get left() {
        return {
          ...this.wrapper,
          left: 0,
        };
      },
      
      get right() {
        return {
          ...this.wrapper,
          right: 0,
        };
      },
    };
    
    console.log(style.left)

    let style2 = {
      wrapper: {
        prop: {
          color: "red",
          position: "absolute",
        },
    
        get top() {
          return {
            ...this.prop,
            top: 0,
          };
        },
        get bottom() {
          return {
            ...this.prop,
            bottom: 0,
          };
        },
      },
    };
    
    console.log(style2.wrapper.bottom);