How to get the current page in FlatList when using pagingEnabled with React-Native?

Sometimes, we want to get the current page in FlatList when using pagingEnabled with React-Native.

In this article, we’ll look at how to get the current page in FlatList when using pagingEnabled with React-Native.

How to get the current page in FlatList when using pagingEnabled with React-Native?

To get the current page in FlatList when using pagingEnabled with React-Native, we can calculate it from the scroll distance.

For instance, we write:

import * as React from 'react';
import { FlatList, Text, View, Dimensions } 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 keyExtractor = (item) => item.id;
  const dimensions = Dimensions.get('window');
  const onMomentumScrollEnd = (e) => {
    const pageNumber = Math.min(
      Math.max(
        Math.floor(e.nativeEvent.contentOffset.x / dimensions.width + 0.5) + 1,
        0
      ),
      flatListItems.length
    );
    console.log(pageNumber);
  };

  return (
    <View style={{ height: 300 }}>
      <FlatList
        horizontal
        data={flatListItems}
        renderItem={renderItem}
        keyExtractor={keyExtractor}
        onMomentumScrollEnd={onMomentumScrollEnd}
      />
    </View>
  );
}

to define the onMomentumScrollEnd which gets the width of the screen with Dimensions.get.

Then we get the page number with

const pageNumber = Math.min(
  Math.max(
    Math.floor(e.nativeEvent.contentOffset.x / dimensions.width + 0.5) + 1,
    0
  ),
  flatListItems.length
)

to divide the horizontal scroll distance e.nativeEvent.contentOffset.x by dimensions.width.

Now when we stop scrolling, we should see the page number logged.

Conclusion

To get the current page in FlatList when using pagingEnabled with React-Native, we can calculate it from the scroll distance.