I am trying to set up a flat list with items having the following properties.
- it has
flex: 1
- it has no specified width (the height may be set in the content for images)
- it is
maxWidth
set - the
width
cannot be forced to100%
because the intent is to have the flat list support multiple columns minWidth
cannot be set since it will prevent shrinking of content if it is too large to fit with number of columns.
The FlatList
is the top level component of a Screen so it will do the collapsing header in iOS. To which
- it takes up the full width
- it has some padding
- the scroll bar should be flushed right (so you can't do
padding
on the FlatList itself
So what I have is something like
const data = Array.from({length: 5}, (v,k) => ({v,k}));
function renderItem({item, index}) {
return (<View style={{
flex:1,
maxWidth: 100,
borderWidth: 1,
backgroundColor: 'red',
// alignSelf: "center" (also shrinks)
}}>
<Text>{item.k}</Text>
</View>)
}
return (<FlatList
style={StyleSheet.absoluteFill}
contentContainerStyle={{
padding: 16,
// alignSelf: center (shrinks content)
}}
renderItem={renderItem}
data={data}
/>)
I'd also like to avoid onLayout
to prevent too much rerenders
https://snack.expo.dev/@trajano/flatlistneedscentering
CodePudding user response:
There's another prop called columnWrapperStyle
which does what I needed.
<FlatList
columnWrapperStyle={{
justifyContent: 'center',
}}
contentContainerStyle={{
paddingVertical: 16,
}}
initialNumToRender={2}
renderItem={renderItem}
data={data}
numColumns={numColumns} //can be set to 3 to force shrinking
ItemSeparatorComponent={() => <View style={{ height: 16 }} />}
keyExtractor={(item) => item.k.toString()}
/>
);
Note that NativeBase does not expose this as a utility prop.