Last active
January 29, 2022 15:30
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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