Search code examples
react-nativereact-navigationscreenreact-native-navigation

Screen starting on the bottom


In react native, I'm using react navigation, and when i'm on the screen "X" and navigate to screen "Y", this is really good, but when i go back to screen "X", that is on the bottom, because when a navigate to screen "Y" i was on the bottom of the screen "X".

What i need: Everytime when i go back to screen "X" this start on the top.

I searched something about this in the docs, however i didnt found nothing about state of screen


Solution

  • You can use useFocusEffect and a ref of your ScrollView to scroll back to the top when the screen comes into focus. Something like:

      const scrollRef = useRef<ScrollView>(null);
    
      useFocusEffect(
       useCallback(() => {
        scrollRef.current?.scrollTo({ x: 0, y: 0, animated: false });
       }, [scrollRef])
      );
    
      // ...
      <ScrollView ref={scrollRef}>