FlatList numColumns not working correctly?

I'm trying to use a FlatList to show a bunch of custom avatars to someone in a grid format, but it looks very strange and I can't figure out how to fix it.

This is how it looks

This is how my FlatList code looks like:

<FlatList
style={{flex: 1}}
data={this.props.usersList}
horizontal={false}
numColumns={3}
columnWrapperStyle={{ marginTop: 10 }}
renderItem={({ item }) => this.renderItem(item)}
keyExtractor={this._keyExtractor}/>

      

and this is what the component for renderItem looks like:

class UserButton extends React.Component {
render() {
    const { item, onPress } = this.props;
    return (
        <TouchableOpacity style={styles.button} onPress={onPress}>
            <Image
                source={(item.avatar) ? { uri: item.avatar } : require('../assets/images/userplaceholder.png')}
                resizeMode='cover'
                style={styles.imageStyle}
            />
        </TouchableOpacity>
    )
}

const styles = {
    button: {
        height: 100,
        width: 100,
        borderColor: '#aaa',
        backgroundColor: '#aaa',
        borderWidth: 2, 
        borderRadius: 50,
        justifyContent: 'center',
        alignItems: 'center',
        marginHorizontal: 5,
    },
    imageStyle: {
        height: 96,
        width: 96,
        alignSelf: 'center',
        borderRadius: 48,
        marginTop: (Platform.OS == 'android') ? 0 : 0.4
    }
}

export default UserButton;

      

Does anyone have any idea?

+3


source to share


2 answers


You can take the width from Dimensions and set that width for the items in your flat list.



const {width} = Dimensions.get('window');
const itemWidth = (width) / 4;

      

+4


source


I was in a similar situation, but now I have the correct grid using flatList, you can take a look at my code below.



<FlatList
    contentContainerStyle={{margin:4}}
    horizontal={false}
    numColumns={4}
    data={this.state.categoryDataSource}
    renderItem={(categoryItem) =>
        <CategoryListItem category={categoryItem.item} mode="small"/>
        }
    keyExtractor={category => category.id}
/>

      

0


source







All Articles