React Native - ListView
React Native - Displaying Lists with FlatList
Section titled “React Native - Displaying Lists with FlatList”This chapter explains how to efficiently display scrollable lists of data in React Native. While you can use ScrollView and map() for short lists, the FlatList component is the recommended way for long or dynamic lists due to its performance optimizations (like item virtualization).
The ListView component mentioned in older tutorials is now deprecated. FlatList is its modern successor.
Using FlatList
Section titled “Using FlatList”FlatList requires two main props: data (an array of data items) and renderItem (a function that returns a React element for each item).
MyListComponent.js
import React, { useState } from 'react';import { FlatList, Text, View, TouchableOpacity, StyleSheet, Alert } from 'react-native';
const MyListComponent = () => { const [people, setPeople] = useState([ { id: '1', name: 'Alice', age: 30 }, { id: '2', name: 'Bob', age: 24 }, { id: '3', name: 'Charlie', age: 35 }, { id: '4', name: 'Diana', age: 28 }, { id: '5', name: 'Edward', age: 40 }, // Add more items to see scrolling behavior { id: '6', name: 'Fiona', age: 22 }, { id: '7', name: 'George', age: 31 }, { id: '8', name: 'Hannah', age: 29 }, { id: '9', name: 'Ian', age: 26 }, { id: '10', name: 'Julia', age: 33 }, ]);
const handleItemPress = (item) => { Alert.alert('Item Pressed', `You selected ${item.name}, aged ${item.age}.`); };
// renderItem function receives an object with an 'item' property const renderListItem = ({ item }) => ( <TouchableOpacity onPress={() => handleItemPress(item)} style={styles.itemContainer}> <Text style={styles.itemName}>{item.name}</Text> <Text style={styles.itemAge}>Age: {item.age}</Text> </TouchableOpacity> );
return ( <View style={styles.container}> <Text style={styles.title}>User List</Text> <FlatList data={people} renderItem={renderListItem} keyExtractor={(item) => item.id} // Important for performance and item stability // Optional props: // ItemSeparatorComponent={() => <View style={styles.separator} />} // ListHeaderComponent={<Text style={styles.listHeader}>Header</Text>} // ListFooterComponent={<Text style={styles.listFooter}>Footer</Text>} // ListEmptyComponent={<Text style={styles.emptyList}>No users found.</Text>} /> </View> );};
const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 20, backgroundColor: '#f0f0f0', }, title: { fontSize: 22, fontWeight: 'bold', textAlign: 'center', marginBottom: 15, color: '#333', }, itemContainer: { backgroundColor: '#ffffff', padding: 20, marginVertical: 8, marginHorizontal: 16, borderRadius: 8, shadowColor: '#000', shadowOffset: { width: 0, height: 1 }, shadowOpacity: 0.22, shadowRadius: 2.22, elevation: 3, }, itemName: { fontSize: 18, color: '#333333', fontWeight: '500', }, itemAge: { fontSize: 14, color: '#666666', marginTop: 4, }, separator: { height: 1, backgroundColor: '#e0e0e0', marginHorizontal: 16, }, listHeader: { fontSize: 18, padding: 10, textAlign: 'center', backgroundColor: '#ddd' }, listFooter: { fontSize: 18, padding: 10, textAlign: 'center', backgroundColor: '#ddd' }, emptyList: { textAlign: 'center', marginTop: 50, fontSize: 16, color: 'gray' }});
export default MyListComponent;Explanation
Section titled “Explanation”data: An array of objects. Each object represents an item in the list.renderItem: A function that takes an object{ item, index, separators }and returns the React component to render for that item. We typically destructureitem.keyExtractor: A function that takes an item and its index, and returns a unique string key for that item. This is crucial for React to manage list items efficiently during updates, additions, or removals. Usingitem.idis common if your data has unique IDs.TouchableOpacity: Used to make each list item pressable, triggering an alert with the item’s details.
When you run this component, you will see a scrollable list of names and ages. Tapping on an item will display an alert with that person’s name and age.
Why FlatList over ScrollView + map()?
Section titled “Why FlatList over ScrollView + map()?”- Performance:
FlatListimplements item virtualization. It only renders items that are currently visible on the screen (plus a few off-screen for smooth scrolling). This significantly improves performance and memory usage for long lists. - Built-in Features:
FlatListoffers features like pull-to-refresh, infinite scrolling support, header/footer components, separators, multi-column layouts, and more, out of the box.
Other Useful FlatList Props
Section titled “Other Useful FlatList Props”ItemSeparatorComponent: Renders a component between each item (e.g., a divider line).ListHeaderComponent: Renders a component at the top of the list.ListFooterComponent: Renders a component at the bottom of the list.ListEmptyComponent: Renders a component when thedataarray is empty.onEndReached: Called when the user scrolls near the end of the list (for infinite scrolling).onRefresh/refreshing: For pull-to-refresh functionality.
For sectioned lists, React Native also provides SectionList. Learn more about FlatList at the official documentation: https://reactnative.dev/docs/flatlist