Sometimes, we want to get the index of the currently visible item in a React Native flat list.
In this article, we’ll look at how to get the index of the currently visible item in a React Native flat list.
How to get the index of the currently visible item in a React Native flat list?
To get the index of the currently visible item in a React Native flat list, we can set the onViewableItemsChange
prop to a function that gets the current visible items.
For instance, we write:
import * as React from 'react';
import { FlatList, Text, View } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';
const flatListItems = Array(200)
.fill()
.map((_, i) => ({ title: i, id: i }));
const Item = ({ title }) => (
<View
style={{
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
}}>
<Text>{title}</Text>
</View>
);
export default function App() {
const renderItem = ({ item }) => <Item title={item.title} />;
const onViewableItemsChanged = ({ viewableItems, changed }) => {
console.log(viewableItems);
console.log(changed);
};
return (
<View>
<FlatList
onViewableItemsChanged={onViewableItemsChanged}
data={flatListItems}
renderItem={renderItem}
keyExtractor={(item) => item.id}
/>
</View>
);
}
to define the onViewableItemsChanged
function that gets the viewableItems
property.
viewableItems
has the items that are current visible on the screen.
changed
has the items that have just entered or left after the last scroll.
They’re both arrays.
Conclusion
To get the index of the currently visible item in a React Native flat list, we can set the onViewableItemsChange
prop to a function that gets the current visible items.