callstack / react-native-pager-view

React Native wrapper for the Android ViewPager and iOS UIPageViewController.
MIT License
2.69k stars 414 forks source link

Passing current / #733

Open klintan opened 1 year ago

klintan commented 1 year ago

Ask your Question

So I'm probably missing something fundamental; but is there an example of passing the currently active page to a child?

I'm doing something very similar to the Basic example, but I would like to pass the current active page to a child. Unfortunately setting a state variable using the selectPageCallback re-renders the parent, and the animated view goes back to the initialPage={0} basically just flickers back.

This happens as soon as you set any kind of state variable.

Would love any pointers or ideas! (quite a react novice so I'm probably just doing something very bad :) )

Some of my sample code:

 const setPage = useCallback(
    (page) =>
      pagerRef.current?.setPage(page),
    []
  );

  const data = [
    {
      key: 0,
      title: 'A good child,
      view: <ChildView nextPage={setPage}></ChildView >,
      ...
    },

<AnimatedPagerView
        style={{ flex: 1 }}
        initialPage={0}
        ref={pagerRef}
        scrollEnabled={true}
        draggable={true}
        onPageScroll={onPageScroll}
        onPageSelected={onPageSelected}
      >
        {useMemo(() => {
          return data.map(({ key, title, view }) => (
            <View key={key}>
              {view}
            </View>
          ));
        }, [data])}
      </AnimatedPagerView>

Now in my world I would do something like this:

 const onPageSelected = useCallback(({ nativeEvent }) => {
    setActivePage(nativeEvent.position);
  }, []);

 <ChildView nextPage={setPage} activePage={activePage}></ChildView >
fusandy commented 1 year ago

facing the same issue 🥲

RemiHin commented 1 year ago

You could set your initialPage to the activePage initialPage={activePage} I think that would solve the flicker.