react-native-grid-flatlist
v0.1.1
Published
A drop-in replacement for React Native FlatList that renders items in a grid without stretching the last row.
Readme
react-native-grid-flatlist
A typed, drop-in grid wrapper around React Native's FlatList that automatically fills the last row with placeholder cells so items never stretch to unexpected widths.
Why?
FlatList with numColumns distributes remaining space evenly across all cells in a row. When the last row has fewer items than numColumns, those items grow to fill the gap — which breaks uniform grid layouts like photo galleries or product grids.
Installation
npm install react-native-grid-flatlist
# or
yarn add react-native-grid-flatlistUsage
import { GridFlatList } from 'react-native-grid-flatlist';
type Photo = {
id: string;
uri: string;
};
<GridFlatList
data={photos}
numColumns={3}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<Image source={{ uri: item.uri }} style={styles.cell} />
)}
/>;Props
GridFlatList accepts all FlatList props with only an extra prop called renderEmptyItem.
| Prop | Type | Default | Description |
| ----------------- | ------------------------------------ | ------------------------------ | ---------------------------------------------------------------------- |
| data | readonly T[] | — | The array of items to render in the grid. |
| renderItem | ListRenderItem<T> | — | Renders each item. Placeholder cells are never passed here. |
| keyExtractor | (item: T, index: number) => string | — | Returns a stable key for each item. Placeholders are keyed internally. |
| numColumns | number | 3 | Number of columns in the grid. |
| renderEmptyItem | () => ReactElement \| null | <View style={{ flex: 1 }} /> | Custom component for the empty cells that fill the last row. |
How it works
GridFlatList pads data with internal placeholder objects so its length is always a multiple of numColumns. Placeholders are filtered out before your renderItem is called, so your own renderer only ever receives real items.
data.length = 10, numColumns = 3
Row 1: [item 0] [item 1] [item 2]
Row 2: [item 3] [item 4] [item 5]
Row 3: [item 6] [item 7] [item 8]
Row 4: [item 9] [ __ ] [ __ ]
↑ placeholder cells, invisible by defaultCustom empty cells
By default empty cells render as a View with flex: 1, which is invisible but holds the correct amount of space. Pass renderEmptyItem when you need a visible treatment:
<GridFlatList
...
renderEmptyItem={() => (
<View style={styles.emptyCell}>
<Text>+</Text>
</View>
)}
/>Contributing
License
MIT
Made with create-react-native-library
