DEV Community

Dima Portenko
Dima Portenko

Posted on • Edited on

8 2

Going back with gestures to a specific screen | React Navigation

Recently, I had a case where I have to navigate from Screen 1 > Screen 2 > Screen 3 > Screen 4 and then go back straight to Screen 1.

Here is expo snack with demo project.

According to the react-navigation docs we can simply use navigation.navigate('Screen1') function to go back to Screen 1.

Image description

Looks good. But what happens if we try to go back with a swipe gesture or a back button?

Image description

With swipe left to right or header back button, we will back to Screen 3. To solve this we can use reset action, which allows us to rewrite the navigation state and remove Screen 2 and Screen 3 from it. Let's simply add the following code to Screen 4.



  useEffect(() => {
    const { routes } = navigation.getState();

    const filteredRoutes = routes.filter(
      route => route.name !== 'Screen3' && route.name !== 'Screen2',
    );

    navigation.reset({
      index: filteredRoutes.length - 1,
      routes: filteredRoutes,
    });
  }, [])


Enter fullscreen mode Exit fullscreen mode
  • { routes } = navigation.getState() get navigation routes state;
  • filteredRoutes = routes.filter remove screens we don't want to have in our stack anymore;
  • index: routes.length - 1 reset index to the latest index in the routes array
  • routes: filteredRoutes reset routes to filtered routes

Image description

That's it! If you like the post please support it with reactions and comments.

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs