Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flatlist rendering data from json api as 3 items per row

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
        }
    })
like image 708
André Abboud Avatar asked Nov 08 '22 03:11

André Abboud


1 Answers

Since you're using flex: 1 and alignItems: center , your layout will look like this After Image

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 After Image

like image 90
Pritish Vaidya Avatar answered Nov 15 '22 11:11

Pritish Vaidya