Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FlatList numColumns doesn't appear to be working correctly?

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

Here's what it looks like

Here's what 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 here's what the component looks like for renderItem:

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;

Anyone have any ideas?

like image 794
Steven Conner Avatar asked Dec 10 '22 11:12

Steven Conner


2 Answers

You can take width from Dimensions and set that width for items of your flatlist.

const {width} = Dimensions.get('window');
const itemWidth = (width) / 4;
like image 170
Anjal Saneen Avatar answered Jan 27 '23 02:01

Anjal Saneen


I was in kind of similar situation, but now I have proper grid using flatList, you can take a look at my code attached 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}
/>
like image 43
Kalpit Champanery Avatar answered Jan 27 '23 03:01

Kalpit Champanery