PagerView works on swipe but not programmatically with setPage

176 views Asked by At

I am working with react-native-pager-view and I am having trouble setting the page programmatically using nativeEvent.setPage()

I have tried a lot of things, went through all the issues regarding it but no luck.

So far I've tried:

  • Changing the children to simple views exactly like the examples
  • Hard set the value in a useEffect and call it constantly
  • Use a separate value to keep track of current page

The swipe gesture is working fine on it and the pages transition, but if I press the button to go forward it doesn't.

If anyone has dealt with this component before please let me know if I'm missing anything.

Code that I'm trying to run. I've changed the View to simple react native view but it didn't work.

//Outside the component
const AnimatedPager = Animated.createAnimatedComponent(PagerView)

  const [activeScreenKey, setActiveScreenKey] = useState(0)
  const pagerViewRef = useRef<PagerView>(null)


  // This function to sync the activeScreenKey if user swipes instead of clicking button
  const getActiveKey = (e: PagerViewOnPageScrollEvent) => {
    const position = e?.nativeEvent?.position
    setActiveScreenKey(position)
  }


  // This calls the `setPage` and also puts it in a state var that I'm tracking
  const setPage = (screenKey: number) => {
    pagerViewRef.current?.setPage(screenKey)
    setActiveScreenKey(screenKey)
  }

  <LinearGradient colors={['#3936BD', '#8448DB']} tw="flex-1">
      <AnimatedPager
        ref={pagerViewRef}
        initialPage={0}
        scrollEnabled={false}
        onPageSelected={getActiveKey}
        tw="flex-1"
      >
        <CustomView
          key="1"
          title={'title'}
          subtitle={'subtitle'}
          buttonTitle={'Next  ➡️'}
          onPress={() => setPage(1)}
        />
       <CustomView
          key="2"
          title={'title'}
          subtitle={'subtitle'}
          buttonTitle={'Next  ➡️'}
          onPress={() => setPage(2)}
        />

      </AnimatedPager>
    </LinearGradient>

0

There are 0 answers