React-Native FlatList
Syntax
import { FlatList } from 'react-native';
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={keyExtractor}
numColumns={numColumns}
// other props
/>
Example
import React from 'react';
import { FlatList, Text } from 'react-native';
const data = [
{ id: '1', title: 'Apple' },
{ id: '2', title: 'Banana' },
{ id: '3', title: 'Cherry' },
// more items
];
function renderItem({ item }) {
return <Text>{item.title}</Text>;
}
function keyExtractor(item) {
return item.id;
}
export default function MyFlatList() {
return <FlatList data={data} renderItem={renderItem} keyExtractor={keyExtractor} />;
}
Output
The MyFlatList
component will output a list of fruit titles:
Apple
Banana
Cherry
Explanation
The FlatList
component is a powerful and flexible component for rendering lists in React Native. It can handle very large lists, as it only renders a subset of the items at a time, and provides optimized scrolling and performance.
The data
prop is an array of data to be rendered in the list. The renderItem
prop is a function that renders each individual item in the list. The keyExtractor
prop is a function that returns a unique key for each item.
Use
The FlatList
component can be used to render any type of list in a React Native app. It is particularly useful for large lists, or lists that are frequently updated.
Some common props that can be used with FlatList
include:
numColumns
: Specifies the number of columns in a grid layout.refreshControl
: Adds a pull-to-refresh control to the list.onEndReached
: Specifies a function to be called when the end of the list is reached.ListEmptyComponent
: Specifies a component to render if the list is empty.
Important Points
One important consideration when using FlatList
is that the renderItem
function should be a pure function, meaning it should not depend on any external state or props. This is because renderItem
may be called multiple times for the same item, and should always produce the same output.
Another consideration is that FlatList
uses a virtualized rendering strategy, meaning that it only renders a subset of the items at any given time. This can be more performant for large lists, but it also means that components in the list need to be lightweight and fast-rendering.
Summary
The FlatList
component is a powerful and flexible component for rendering lists in React Native. It provides optimized performance for large lists, and supports a wide range of props for customizing the list's behavior.