React Native inconsistent size of items in FlatList when using numColumns and margin

36 Views Asked by At

When the last row has 1 or 2 items when using numColumns={3} they are slightly bigger

const BookList = () => {
  ...
  const renderItem = (item: any) => {
    return (
      <View style={styles.imageContainer}>
        <Image 
          source={{uri: item.smallThumbnail}}
          style={styles.image} resizeMode='stretch' />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <FlatList style={styles.list}
        data={books}
        keyExtractor={(item) => item.id.toString()}
        numColumns={3}
        renderItem={({item}) => renderItem(item)}
      />
    </View>
  );
...
const styles = StyleSheet.create({
    container: {
    flex: 1
  },
  list: {
    flex: 1,
  },
  imageContainer: {
    flex: 1/3,
    margin: 5
  },
  image: {
    borderRadius: 5,
    aspectRatio: 6 / 9
  }
});

issue image

tried margin on image not imageContainer, this gave even more inconsistant spacing, like more vertically then horizontally and none at the left.

1

There are 1 best solutions below

2
user18309290 On

margin in the container affects the width of the element(s). Move margin to image style.

const App = () => {
  return (
    <View style={styles.container}>
      <FlatList
        data={[...Array(5).keys()].map((i) => `https://picsum.photos/200/300?random=${i}`)}
        numColumns={3}
        renderItem={({item}) =>   
          <View style={styles.imageContainer}>
            <Image style={styles.image} source={{uri: item}}/>
          </View>
        }
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  imageContainer: {
    flex: 1/3
  },
  image: {
    borderRadius: 5,
    aspectRatio: 6 / 9,
    margin: 5
  }
});