— React Native, FlatList, Lists — 1 min read
When building mobile applications, it is common to display lists of data such as contacts, messages, or products. In React Native, the FlatList
component provides an efficient way to display these lists while minimizing performance issues. In this article, we will explore how to use the FlatList
component in React Native.
To get started with FlatList
, you need to import the component from the react-native
library:
1import { FlatList } from 'react-native';
Once you have imported the component, you can start using it in your code.
The simplest way to use FlatList
is by passing an array of data to the data
prop and a function that returns a component for each item in the list to the renderItem
prop:
1const data = [2 { id: 1, name: 'John' },3 { id: 2, name: 'Jane' },4 { id: 3, name: 'Bob' },5];6
7const renderItem = ({ item }) => {8 return (9 <View>10 <Text>{item.name}</Text>11 </View>12 );13};14
15<FlatList data={data} renderItem={renderItem} />;
In the example above, we pass an array of objects to the data
prop, and a function that returns a View
component containing a Text
component that displays the name of each item to the renderItem
prop. The FlatList
component will automatically render each item in the list using the provided renderItem
function.
When rendering a large number of items, it is important to provide a unique key
prop to each item. This allows React Native to efficiently update the component tree when changes occur. To do this, we can use the keyExtractor
prop:
1const keyExtractor = (item) => item.id.toString();2
3<FlatList4 data={data}5 renderItem={renderItem}6 keyExtractor={keyExtractor}7/>;
In the example above, we pass a function to the keyExtractor
prop that extracts the id
property from each item and converts it to a string. This ensures that each item has a unique key
prop.
The FlatList
component has many other props that can be used to customize its behavior, including:
numColumns
: Specifies the number of columns to use when displaying the items.horizontal
: Determines whether the list should be displayed horizontally or vertically.refreshing
: Determines whether the list should show a refresh indicator.onRefresh
: A callback function that is called when the user pulls down on the list to refresh it.In this article, we learned how to use the FlatList
component in React Native to efficiently display large lists of data. We explored the basic usage of the component, how to extract keys for each item, and some of the other available props. With FlatList
, you can easily display lists of any size with minimal performance issues.