React Navigation: Scroll to top if tab is the same as active tab

For who is looking for a solution for react native, if you are using react navigation, you need to import ScrollView, FlatList or SectionList from react-navigation instead of react-native.

eg.

import { FlatList } from 'react-navigation';

You can find the details on the docs: https://reactnavigation.org/docs/4.x/scrollables/

UPDATE

If you are using react navigation v5

import * as React from 'react';
import { FlatList } from 'react-native';
import { useScrollToTop } from '@react-navigation/native';

function CustomComponent() {
  const ref = React.useRef(null);

  useScrollToTop(ref);

  return <FlatList ref={ref} {/* settings */} />;
}

docs: https://reactnavigation.org/docs/use-scroll-to-top


React Navigation 5.x

The simplest solution they have provided is, just pass the ref of your scrollable component to their useScrollToTop hook.

import * as React from 'react';
import { ScrollView } from 'react-native';
import { useScrollToTop } from '@react-navigation/native';

function Albums() {
  const ref = React.useRef(null);

  useScrollToTop(ref);

  return <ScrollView ref={ref}>{/* content */}</ScrollView>;
}

Snack.expo.io Example

Documentation


You can create your tab navigator as follow:

const TabNav = TabNavigator({
   // config
},
{
   navigationOptions: ({ navigation }) => ({
        tabBarOnPress: (scene, jumpToIndex) => {
            // Called when tab is press
        },
    }),
});

In order to scroll to top, you can check this solution:

  1. https://github.com/react-navigation/react-navigation/issues/2955#issuecomment-343422076
  2. https://snack.expo.io/HJp9mEQkG