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

mathew picture mathew · Apr 12, 2017 · Viewed 14.5k times · Source

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)?

Answer

A. Goodale picture A. Goodale · Apr 12, 2017

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.