In this lesson, you will learn how to transform a standard, single-column vertical list into a clean, multi-column grid interface using the numColumns property.
Up until now, you have worked with FlatList to render data in a single vertical stream. However, mobile designs often require a grid layout—like a photo gallery or a product selection screen—where items sit side-by-side.
Leveraging the numColumns Prop
The FlatList component has a built-in prop called numColumns. When you provide an integer greater than 1 to this prop, React Native automatically calculates the width of your list items so they fit perfectly across the screen in equal columns.
Here is how you would set up a basic grid:
import { FlatList, View, Text, StyleSheet } from 'react-native';
const data = [{ id: '1' }, { id: '2' }, { id: '3' }, { id: '4' }];
const Grid = () => (
<FlatList
data={data}
numColumns={2} // This creates the grid!
renderItem={({ item }) => (
<View style={styles.item}>
<Text>Item {item.id}</Text>
</View>
)}
keyExtractor={(item) => item.id}
/>
);
const styles = StyleSheet.create({
item: {
flex: 1,
margin: 5,
height: 100,
backgroundColor: '#ccc',
justifyContent: 'center',
alignItems: 'center',
},
});
Essential Considerations
When switching to a grid layout, keep these two things in mind:
- Flexing Items: Ensure your
renderItemcontainer has aflex: 1style. This allows the item to grow and shrink to fill the space allocated by theFlatListcalculation. - Spacing: Because the layout is now multi-dimensional, standard margins work differently. You may notice your items push against each other. Using
margininside your item style is a great way to create a "gutter" or gap between grid cells.
Note that when using numColumns, you cannot use the inverted prop or horizontal scrolling, as the component is specifically optimized for this vertical grid structure.
Key Takeaway: By setting the numColumns prop on a FlatList, you can instantly convert a vertical scrollable list into a multi-column grid without manually calculating item widths.