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.
Looks good. But what happens if we try to go back with a swipe gesture or a back button?
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,
});
}, [])
-
{ 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
That's it! If you like the post please support it with reactions and comments.
Top comments (0)