Categories
JavaScript Answers React Native Answers

How to add a ListView grid in React Native?

Spread the love

Sometimes, we want to add a ListView grid in React Native

In this article, we’ll look at how to add a ListView grid in React Native.

How to add a ListView grid in React Native?

To add a ListView grid in React Native, we should use a FlatList instead with some flexbox styles.

For instance, we write:

import * as React from 'react';
import { View, FlatList, Text, StyleSheet, Dimensions } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

const numColumns = 3;
const size = Dimensions.get('window').width / numColumns;

const styles = StyleSheet.create({
  itemContainer: {
    width: size,
    height: size,
  },
  item: {
    flex: 1,
    margin: 3,
    backgroundColor: 'lightblue',
  },
});

const data = Array(200)
  .fill()
  .map((_, i) => ({ id: i, value: i }));

export default function App() {
  return (
    <FlatList
      data={data}
      renderItem={({ item }) => (
        <View style={styles.itemContainer}>
          <Text style={styles.item}>{item.value}</Text>
        </View>
      )}
      keyExtractor={(item) => item.id}
      numColumns={numColumns}
    />
  );
}

to add the itemContainer style property that sets the width and height of the container.

Then we render a FlatList with the data array set as the value of the data prop.

Then we set the renderItem prop to a function to render items in the FlatList.

We set numColumns to set the number of columns.

keyExtractor is set to a function that returns the unique key for each item.

Conclusion

To add a ListView grid in React Native, we should use a FlatList instead with some flexbox styles.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *