How to catch the number of the page that i'm in? ViewPager React Native

4.8k Views Asked by At

I'm using ViewPager by react-native-community to scroll down my page, but I'm having trouble when catching the page that the user is in, in the API there is a showPageIndicator: boolean but only for IOS, i figure we can catch the number in the IOS by this bool there is some way i can catch the number.

https://github.com/react-native-community/react-native-viewpager

<ViewPager
            initialPage={0}
            orientation="horizontal"
            scrollEnabled
            onPageSelected={changePage}
>
2

There are 2 best solutions below

0
Zohaib Ahmad On
  function Component(props) {
  //by default the initialPosition props is 0, set as initial value of currentPage 
  too...
   const [currentPage, setCurrentPage] = useState(0);

 {... component code } 
 const onPageScroll = (event) => {
const {position} = event.nativeEvent;
  if(position !== currentPosition) {
   setCurrentPosition(position);
 }
 } 

return (
<ViewPager onPageScroll={onPageScroll}>
  ... your pages
</ViewPager> 
)

}

by this the props onPageScroll you will get the current page of viewpager

1
Shoaib Ahmed On

You can use OnPageSelected Prop to get position.

<ViewPager
        initialPage={0}
        orientation="horizontal"
        scrollEnabled
        onPageSelected={e => {console.log("Current page index", e.nativeEvent.position)}}>