Hello all i am fetching data from json api and i am using flatlist to render items . i am using numColumns
property to display 3 items per row
but let's suppose i have 7 or 8 items
i am having trouble with rendering. the layout i want to be displayed is like this
X X X
X X X
X X
but what i am getting is this: layout
Here is my code:
_renderItem = ({ item, index }) => (
<View style={categorystyles.Category} key={index}>
<TouchableOpacity activeOpacity={.5}
onPress={() => this.props.navigation.navigate('ListingPerCategory', { catid: item.id })}>
{item.category_app_icon ? <Image style={categorystyles.CategoryImg}
source={{ uri: `${item.category_app_icon}` }} /> :
<Image style={categorystyles.CategoryImg}
source={require('../assets/coffeecup.png')} />}
</TouchableOpacity>
<Text style={{ marginTop: 5 }}>{escape(item.name).replace('%20', ' ').replace('%26amp%3B%20', ' ')}</Text>
</View>
)
render(){
return(
<FlatList
horizontal={false}
data={this.state.categories}
keyExtractor={(item, index) => item.id}
numColumns={3}
renderItem={this._renderItem}
/>
)
}
const styles = StyleSheet.create({
Category: {
flex:1,
justifyContent: 'center',
alignItems:'center',
margin:5
},
CategoryImg: {
resizeMode: 'contain',
width: 50,
height: 50
}
})
Since you're using flex: 1
and alignItems: center
, your layout will look like this
Therefore the items
inside it will be aligned to center vertically and horizontally based on the items layout.
Instead you need to check for the width
of the device and add layout based on that.
In your styles
Category: {
flex:1,
maxWidth: Dimensions.get('window').width / 3 - 10, // Width / 3 - (marginLeft and marginRight for the components)
justifyContent: 'center',
alignItems:'center',
margin:5
},
After adding this style , layout will look like this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With