I want to add some spacing in react native using flatlist, but it seems more difficult than it should be at the moment.
Turns out that react native does not support gap
property, which makes this very complicated.
I solved the horizontal spacing, by making my item 49.5%
wide which means I have 1%
space horizontally, now how do I do the same for vertical spacing?
Most importantly how do i ensure that both horizontal and vertical "gaps" are EQUAL.
const renderItem = ({ item }) => (
<Pressable onPress={() => alert(item.name)} style={{
aspectRatio: 1,
width: "49.5%",
position: "relative",
}}>
<Image
style={{
width: "100%",
height: "100%"
}}
source={{
uri: item.url,
}}
/>
<View
style={{
position: "absolute",
zIndex: 3,
bottom: 0,
paddingHorizontal: 2,
paddingVertical: 8,
flexDirection: "row",
// justifyContent: "center",
alignItems: "center",
}}
>
<Text style={{ color: "white", fontSize: 16 }}>{item.name}</Text>
</View>
</Pressable>
);
export default function App() {
return <FlatList
numColumns={2}
data={people}
renderItem={renderItem}
columnWrapperStyle={{
justifyContent: "space-between"
}}
/>
}
3
Answers
You could use the
ItemSeparatorComponent
property of theFlatList
component to make the vertical gap. This property is a component rendered in between eachFlatList
item, but not at the top, bottom, right or left. You can read more about it on the documentation.Change the
FlatList
to this:In order for the horizontal space to be given the same size as the vertical space, you can move one column away from the other using
padding
:paddingRight
of half the size of the vertical space.paddingLeft
instead ofpaddingRight
.Here’s the code:
Some points:
View
component was created because if the Pressable had thepadding
property, the vertical gap would be pressable too.width: '50%'
because this makes the images took half the screen’s width.padding
instead ofmargin
because thewidth
still is50%
, so margin would push the elements beyond the right edge of the screen. If you use a greater value like40
instead of10
andmargin
instead ofpadding
you can see the problem.This was the visual result.
P.S.: I ran your app in my machine with some URL images I got on Unsplash and it worked: the vertical gap was created by the ItemSeparatorComponent.
P.S. 2: I made some changes to the code and now both horizontal and vertical gaps are equal sized. This was the result. In addition, I changed my answer.
The
ItemSeparatorComponent
takes care of the spacebetween rows
but not between columns. Since we have a two columnFlatList
, we can create the same space as provided by theItemSeparatorComponent
between two columns by adding it as amarginRight
to all the elements that have anodd index
.The key part is the
marginRight: index % 2 !== 0 ? 0 : 10
for the parent view of each item in the render function.Simple solution for me was to just added margin around each item and negative margin around container.