Search code examples
react-nativereact-navigationreact-native-flatlist

scrollTopTop listener not working in component (React-Native)


I used to have the same implementation in ScrollView and it was working and when I changed to flatlist my scroll to top stopped working

I am using an event register, since I have nested navigation.

Here is my implementation: (in Navigation.js)

<Tab.Screen
  name="Home"
  component={HomeNavigation}
  listeners={({navigation, route}) => ({
    tabPress: () => {
      const isAtFirstScreenOfStack =
        !route.state || route.state?.index === 0;
      if (navigation.isFocused() && isAtFirstScreenOfStack) {
        console.log('Scrolling to Top');
        EventRegister.emit('scrollToTop', 'it works!!!');
      }
    },
  })}

in the component where I have the list:

let scrollViewRef = useRef(null);
let scrollToTopListener = useRef(null);

useFocusEffect(
useCallback(() => {
  scrollToTopListener.current = EventRegister.addEventListener(
    'scrollToTop',
    () => {
      if (scrollViewRef.current) {
        scrollViewRef.current.scrollTo({y: 0, animated: true});
      }
    },
  );

  return () => {
    EventRegister.removeEventListener(scrollToTopListener.current);
  };
}, []),

);

 ...
   <FlatList
     ref={(ref) => (scrollViewRef = ref)}
     ...

Solution

  • Use scrollToOffset in FlatList

    ref.current.scrollToOffset({y:0,animated:true})