2

I'm using react-native-pager-view and I try to setPage on my index change but it doesn't work on iOS devices. Flow is like this that I try to pass the index as a props to my custom ViewPager and I'm using the UseEffect to setPage for my ViewPager which is not working on iOS and I have no idea why.

    // @flow
    import React, { useEffect, useRef } from 'react';
    import { StyleSheet, View, I18nManager } from 'react-native';
    import PagerView, { PagerViewOnPageSelectedEvent } from 'react-native-pager-view';
    
    type Props = {
        children: React$Node,
        index: number,
        onIndexChange: (index: number) => void,
    };
    

    const MyViewPager = ({ children, index, onIndexChange }: Props) => {
        const viewPagerRef = useRef<PagerView>(null);
    
        useEffect(() => {
            viewPagerRef.current?.setPage(index);
        }, [index]);
    
     
        const onPageSelect = (e: PagerViewOnPageSelectedEvent) => {
            onIndexChange(e.nativeEvent.position);
        };
    
        return (
            <View style={styles.container}>
                <PagerView
                    ref={viewPagerRef}
                    style={styles.container}
                    initialPage={index}
                    orientation="horizontal"
                    onPageSelected={onPageSelect}
                >
                    {children}
                </PagerView>
            </View>
        );
    };
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
        },
    });
    
    export default MyViewPager;

Niloufar
  • 512
  • 1
  • 5
  • 24

3 Answers3

0

the @next version "^6.0.0-rc.0" worked for me

yarn add react-native-pager-view@^6.0.0-rc.0

or if you are using npm

npm i react-native-pager-view@^6.0.0-rc.0
amr dar
  • 1
  • 1
0

If you have layoutDirection="rtl" prop in PagerView. Try Removing it e.g

Not working code

      <PagerView
        initialPage={0}
        layoutDirection="rtl"
        ref={ref}
        scrollEnabled={false} >

Working code for me

<PagerView
    initialPage={0} 
    ref={ref} 
    scrollEnabled={false} >

This solution worked for me.

Pratik Sanap
  • 107
  • 8
0

I had a workaround something like

   useEffect(() => {
     const setPage = async () => {
       try {
         pagerRef.current.setPageWithoutAnimation(photoIndex.current);
       } catch (e) {
         console.error(e);
       }
     };
     setTimeout(() => {
       setPage();
     }, 0), [images]);

I think the set time out with 0 has something to do with the way the function gets loaded. It worked for me. If someone knows the details about this please comment. I'll ask chat gpt later prolls

ryancoder
  • 1
  • 2