'How to call scrollTo function from react-navigation tab bar

I have create a function which scrolls a ScrollView to a set position when it is called (near top). I would like for the function to be called from the react-navigation tab bar. Calling the function is easy, but I am struggling to get it to communicate with the scrollRef from the screen component.

Here's my snack: https://snack.expo.dev/@dazzerr/scroll-to-top-function

You'll find this function in App.js which is called when the tab bar is pressed:

const onTabPress = () => {
  scrollRef.current?.scrollTo({ // how do I get ref={scrollRef} from component.js ScrollView?
    y: 0,
    animated: true,
  });
};

and in component.js is the ScrollView in question:

  <ScrollView
    ref={scrollRef}
    style={styles.container}
    scrollEventThrottle={16}
  >
      {ScreenContent()}
  </ScrollView>

How can I get the scrollRef from component.js called from inside the onTabPress function from app.js? 🤔



Solution 1:[1]

You'll need to pass the function through react-navigation setParams like this:

This goes inside your createBottomTabNavigator:

  tabBarOnPress: (scene, jumpToIndex) => {
      scene.navigation.state.params.scrollToTop(); // Here's the magic!
  },

And this inside your component:

  useEffect(() => {
    props.navigation.setParams({
      scrollToTop: () => {
        onTabPress();
      },
    });
  }, []);

  const onTabPress = () => {
    scrollRef.current?.scrollTo({
      y: 600, // whatever number you want here
      animated: true,
    });
  };

Of course don't forget to add the scrollRef to your ScrollView, and make sure that your ScrollView is from react-native and not react-navigation. You might also want to add conditionals inside the tabBarOnPress such as:

if (
  isFocused &&
  typeof route.routes[0]?.params?.onTabBarPress !== "function"
)

But that's your doing ?

Here's a working snack: https://snack.expo.dev/@dazzerr/ontabpress-scrollto

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dazza