React-Native: Get current page in FlatList when using pagingEnabled

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.

Leave a Comment

tech