Reputation: 53
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
}
})
Upvotes: 5
Views: 2432
Reputation: 2456
if you want to be displayed like this
X X X
X X X
X X
not
X X X
X X X
X X
just change the style:
const styles = StyleSheet.create({
Category: {
flex:1,
justifyContent: 'flex-start',
alignItems:'center',
margin:5
},
CategoryImg: {
resizeMode: 'contain',
width: 50,
height: 50
}
})
Upvotes: 0
Reputation: 22209
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
Upvotes: 2
Reputation: 4278
Flatlist lazy loads the items - which means they render when you scroll. This is the behaviour of flat list due to performance. If you are interested to render all together, you should use ScrollView instead
Upvotes: -1