Is there any better way to make same gap spaces between items in flex display?

Viewed 3982
  1. use flexbox (because it is react-native)
  2. parent container's width is a percentage
  3. item count can be 4/5/6/7..
  4. same gap spaces between items
  5. like picture below

enter image description here

Here is my code:

const styles = {
container: {
  width: screenWidth * 0.9,
  flexWrap: 'wrap',
  flexDirection: 'row'
},
item: {
  backgroundColor: 'red',
  height: 120,
  width: (width * 0.9 - 20) / 3,
  marginBottom: 10
}
}

<View style={styles.container}>
  {items.map((item, idx) =>
    <View style={[styles.item, { marginHorizontal: idx % 3 === 1 ? 10 : 0}]} />
  )}
</View>

Is there another better way to realize this layout?

1 Answers

kindly check out this demo: https://snack.expo.io/@immynk/demo

As per require height width you can use in View component inside Flatlist and also you can put numColumns as per you want

import * as React from 'react';
import { Text, View, StyleSheet, FlatList, Dimensions } from 'react-native';
import Constants from 'expo-constants';

const DATA = [
  {
    key: 1,
  },
  {
    key: 2,
  },
  {
    key: 3,
  },
  {
    key: 4,
  },
  {
    key: 5,
  },
  {
    key: 6,
  },
];

export default class App extends React.Component {
  render() {
    return (
      <View>
        <FlatList
          showsVerticalScrollIndicator={false}
          data={DATA}
          numColumns={3}
          renderItem={({ item, index }) => {
            return (
              <View
                style={{
                     backgroundColor: "red",
                    paddingHorizontal: 5,
                    paddingVertical: 5,
                    flexDirection: "row",
                    height:130,
                    width:130

                }}>
               <View style={{backgroundColor:"white",width:"100%"}}>

                </View>

              </View>
            );
          }}
          keyExtractor={item => item.key}
        />
      </View>
    );
  }
}
Related