React native, set height for flatlist container according to space contain by item

Viewed 201

I'm trying to set height of flatlist container equal to height equal to space taken by it's item like in the image below

enter image description here

but I'm getting the same result

enter image description here

2nd item container took same space as 1st item container can someone tell me how to fix that? below is my code

<FlatList
        data={data}
        keyExtractor={(item) => item._id.toString()}
        renderItem={({ item }) => {
    return (
      <TouchableOpacity
        style={styles.container}
        onPress={() =>
          navigation.navigate(strings.VIEW_QUOTE, {
            image: item.image_url,
            text: item.description,
          })
        }
      >
        <Image
          source={{
            uri: item.image_url,
          }}
          style={{
            height: moderateScaleVertical(153),
            resizeMode: "stretch",
          }}
        />
        <Text style={styles.text}>{item.description}</Text>
      </TouchableOpacity>
    );
  }}
        numColumns={2}
        style={{
          marginHorizontal: moderateScale(12),
        }}
      />
....
const styles = StyleSheet.create({
  container: {
    overflow: "hidden",
    marginHorizontal: moderateScaleVertical(4),
    marginTop: moderateScaleVertical(20),
    borderWidth: 1,
    borderColor: colors.blackOpacity15,
    borderRadius: 5,
    flex: 1,
  },
  text: {
    ...commonStyles.fontSize15,
    fontFamily: fontFamily.medium,
    marginHorizontal: moderateScale(6),
  },
});
1 Answers

You can put an onLayout function to FlatList.

const [flatListHeight, setFlatListHeight] = useState(0);

const onLayout = (e) => {
   setFlatListHeight(e.nativeEvent.layout.height);
}

return (
  <FlatList onLayout={onLayout} />
);
Related