I have a FlastList that looks like this:
<FlatList
pagingEnabled={true}
horizontal={true}
showsHorizontalScrollIndicator={false}
data={[ {key:"A"}, {key:"B"} ]}
renderItem={ ({item, index}) => <MyComponent /> }
/>
I have the width of the component set so that only one page shows up on screen at a time. How do I determine what the current page is (or alternatively, the current component being shown)?
contentOffset; let index = Math. floor(contentOffset. x / 300);
import React from 'react';import {SafeAreaView,StyleSheet,ScrollView,View,Text,StatusBar,FlatList,TouchableOpacity} from 'react-native'; We now need to create a method named “LoadRandomData” and use fetch to retrieve data from our random data api.
In Flatlist set scrollsToTop={false} this will retain position when you navigate back from detail screen.
The ItemSeparatorComponent prop of FlatList is used to implement the separator between the elements of the list. To perform the click event on list items, we use onPress prop to Text.
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.
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 /> }
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With