React-Native: Get current page in FlatList when using pagingEnabled
You can use onMomentumScrollEnd of Flatlist to detect page change event.
And based on the mobile dimensions_width and listItem size, calculate the pageNumber using below formula.
let onScrollEnd = (e) => {
let pageNumber = Math.min(Math.max(Math.floor(e.nativeEvent.contentOffset.x / dimensions_width + 0.5) + 1, 0), listItems.length);
console.log(pageNumber);
}
<FlatList
pagingEnabled
horizontal
onMomentumScrollEnd={onScrollEnd}
data={listItems}
renderItem={ ({item, index}) => <MyComponent /> }
/>
I built a component with a VirtualizedList
like yours, with paging enabled. I used the ScrollView's onMomentumScrollEnd
handler to determine the current page based on the contentOffset. The onMomentumScrollEnd
handler is called when the scroll animation stops after the user swipes between pages. It has an event object like the standard onScroll
event. You can use the nativeEvent.contentOffset.x
to determine which page you are on like this:
class Example extends React.Component {
onScrollEnd(e) {
let contentOffset = e.nativeEvent.contentOffset;
let viewSize = e.nativeEvent.layoutMeasurement;
// Divide the horizontal offset by the width of the view to see which page is visible
let pageNum = Math.floor(contentOffset.x / viewSize.width);
console.log('scrolled to page ', pageNum);
}
render() {
return
<VirtualizedList
horizontal
pagingEnabled
onMomentumScrollEnd={this.onScrollEnd} />
}
}
I left other VirtualizedList
props to save space. The FlatList
component is built on VirtualizedList
, so the example should work for you.