Skip to content

Instantly share code, notes, and snippets.

@DJanoskova
Created May 8, 2023 20:15
Show Gist options
  • Select an option

  • Save DJanoskova/f949649c5b1d830d4682ef1632dbd65e to your computer and use it in GitHub Desktop.

Select an option

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
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