Skip to content

Instantly share code, notes, and snippets.

@nelsonprsousa
Last active January 29, 2022 15:30
Show Gist options
  • Save nelsonprsousa/80f03e785609ad26f47a582074712b36 to your computer and use it in GitHub Desktop.
Save nelsonprsousa/80f03e785609ad26f47a582074712b36 to your computer and use it in GitHub Desktop.
The expected native behavior of scrollable components is to respond to events from navigation that will scroll to top when tapping on the active tab as you would expect from native tab bars. Works with react-native-navigation.
import { useEffect, useRef } from 'react';
import { ScrollView } from 'react-native';
import { Navigation } from 'react-native-navigation';
const useScrollToTop = ({
selectedTabIndex,
}: {
selectedTabIndex: number;
}): React.RefObject<ScrollView> => {
const scrollViewRef = useRef<ScrollView>(null);
useEffect(() => {
const subscription = Navigation.events().registerBottomTabSelectedListener(
event => {
if (
event.selectedTabIndex === selectedTabIndex &&
event.unselectedTabIndex === selectedTabIndex
) {
if (scrollViewRef && scrollViewRef.current) {
scrollViewRef.current.scrollTo({
x: 0,
y: 0,
animated: true,
});
}
}
},
);
return () => {
subscription.remove();
};
}, [selectedTabIndex]);
return scrollViewRef;
};
export default useScrollToTop;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment