Search code examples
reactjsreact-nativereact-native-flexboxreact-native-stylesheet

Adding items into n column grids using flex


I am trying to create a list of items which looks similar to the below image.

Currently I am creating a RowComponent and including ItemContainer component inside to create the mentioned effect.

const styles = StyleSheet.create({
  containerStyle: {
    display: 'flex',
    flexDirection: 'row',
  },
});

const RowComponent = () => {
  const { containerStyle } = styles;

  return (
    <View style={containerStyle}>
      <ItemContainer />
      <ItemContainer />
    </View>
  );
};

Main screen view

<View style={containerStyle}>
  <RowComponent />
  <RowComponent />
</View>

I find this method very inefficient therefore I hope to know how I can create this effect by just duplicating the ItemContainer to create the mentioned effect.

eg:

<View style={containerStyle}>
  <ItemContainer />
  <ItemContainer />
  <ItemContainer />
  <ItemContainer />
</View>

enter image description here


Solution

  • how I can create this effect by just duplicating the ItemContainer to create the mentioned effect.

    You can set flexWrap property to wrap in your containerStyle. Like this:

      containerStyle: {
        display: 'flex',
        flexDirection: 'row',
        flexWrap:"wrap"
      },
    

    And now without RowComponent you can achieve the same layout.


    <View style={styles.containerStyle}>
    
        <View style={styles.itemContainer} />
        <View style={styles.itemContainer} />
        <View style={styles.itemContainer} />
        <View style={styles.itemContainer} />
        <View style={styles.itemContainer} />
    
    </View>
    

    Style:

      containerStyle: {
        display: 'flex',
        flexDirection: 'row',
        flexWrap:"wrap"
      },
      itemContainer: {
        width:"45%",
        height:80,
        marginRight:"5%",
        marginBottom:10,
        backgroundColor:"red"
      }
    

    enter image description here