Created
May 8, 2023 20:15
-
-
Save DJanoskova/f949649c5b1d830d4682ef1632dbd65e to your computer and use it in GitHub Desktop.
Provide a FlatList ref to listen to route param change and scroll to the list's top
This file contains hidden or 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 {RouteProp, useRoute} from '@react-navigation/native'; | |
| import {RefObject, useEffect} from 'react'; | |
| import {FlatList} from 'react-native'; | |
| export const useScrollToTop = <T extends RouteProp<any>>( | |
| listRef: RefObject<FlatList>, | |
| ) => { | |
| const route = useRoute<T>(); | |
| useEffect(() => { | |
| if (route.params?.scrollToTop) { | |
| listRef.current?.scrollToOffset({offset: 0, animated: true}); | |
| } | |
| }, [route.params?.scrollToTop]); | |
| }; | |
| // use like this | |
| // interface FeedScreenProps { | |
| // route: RouteProp<HomeStackParamList, 'Feed'>; | |
| // } | |
| // export const FeedScreen = ({route}: FeedScreenProps) => { | |
| // const listRef = useRef<FlatList>(null); | |
| // useScrollToTop<RouteProp<HomeStackParamList, 'Feed'>>(listRef); | |
| // return ( | |
| // <FlatList | |
| // ref={listRef} | |
| // ... | |
| // /> | |
| // ); | |
| // }; | |
| // invoke like this | |
| // navigation.navigate('Feed', { | |
| // scrollToTop: new Date().toISOString(), | |
| // }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment