React-Native ListView
Syntax
The ListView component is no longer officially supported in React Native versions 0.62 and higher. Instead, developers are encouraged to use the FlatList or SectionList components.
import { FlatList } from 'react-native';
<FlatList
data={/* an array of data */}
renderItem={/* a function to render a single item */}
/>
Example
import { FlatList, StyleSheet, Text, View } from 'react-native';
function MyList(props) {
const data = [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' },
];
const renderItem = ({ item }) => (
<View style={styles.item}>
<Text>{item.text}</Text>
</View>
);
return (
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={(item) => item.id.toString()}
/>
);
}
const styles = StyleSheet.create({
item: {
padding: 10,
marginVertical: 5,
backgroundColor: '#f9c2ff',
},
});
export default MyList;
Output
The MyList
component rendered with the example data above would display a list of three items.
Explanation
The FlatList
component is used to display a collection of data that can be scrolled through, unlike the ScrollView
component which renders all items at once.
The data
prop should be an array of data objects. The renderItem
prop should be a function which takes each data object and returns a component to render it.
The keyExtractor
prop should be a function that returns a unique key for each item in the data array.
Use
The FlatList
component is ideal for displaying large amounts of dynamically fetched data. It performs well with large datasets because it only renders the items currently visible on the screen. As the user scrolls, it dynamically renders new items and removes old ones from the DOM.
The FlatList
component is highly customizable and can be used to implement many different list structures, including grid views, multi-column layouts, and horizontal scrolling.
Important Points
- The
FlatList
component can automatically handle loading more data as the user scrolls with theonEndReached
prop. - The
FlatList
component can support section headers and footers with therenderSectionHeader
andrenderSectionFooter
props. - The
FlatList
andSectionList
components support item animations with theAnimated
API.
Summary
The FlatList
component is a highly customizable and performant way to display lists of data in React Native applications. Although the ListView
component is no longer officially supported, the FlatList
and SectionList
components can be used to implement all of its previous functionality.