Search code examples
javascriptreactjsreact-nativeflexboxreact-native-flexbox

How to layout with nine square view in React Native?


How to achieve the square layout like the image below?

Or any related package exist?

square layout


Solution

  • I am using the combination of ScrollView and flexbox to achieve my static grid view.

    import {Dimensions} from 'react-native';
    
    ....
    
    return (
      <ScrollView>
        <View style={styles.container}>
          {
            this.props.categories.map((category, index) => {
              return (
                <TouchableOpacity
                  key={index}
                  style={styles.item}
                  onPress={() => {}}
                >
                  <Image
                    style={styles.itemIcon}
                    source="..."
                  />
                  <Text style={styles.itemTitle}>
                    {category.name}
                  </Text>
                </TouchableOpacity>
              )
            })
          }
        </View>
      </ScrollView>
    )
    
    var styles = StyleSheet.create({
        container: {
            flexDirection: 'row',
            flexWrap: 'wrap'
        },
        item: {
            width: Dimensions.get('window').width * 0.5,
            height: 100,
            borderWidth: 1,
            borderColor: "lightgray",
            alignItems: 'center',
            justifyContent: 'center'        
        },
        itemIcon: {
            width: 100,
            height: 100,
            resizeMode: 'contain'
        },
        itemTitle: {
            marginTop: 16,
        },
    });