[English] React Navigation — Navigate to Different Nested Stacks

Garry Priambudi
React Native Zone - English
2 min readApr 28, 2018
Source: https://github.com/react-navigation/react-navigation/issues/983#issue-220697445

Want to read this tutorial in Indonesian?

Have your ever encountered an error “Error: There is no route defined for key”? This happens because we navigate to different Nested Stacks. Because in one stack, we can only navigate to the route that is in one stack. If we navigate to another stacks, then this error occurs.

In doing some of the projects I’ve worked on, there are quite a few need cases I’ve encountered. That requires me to navigate to different Nested Stacks. Most cases will occur if we use TabNavigator and StackNavigator in the application project being developed. Moreover using DrawerNavigator, there will be many error conflicts like this if it is not clever to set the order of routes in each Nested Stacks to fit the needs.

Study Case

We have a MainNavigator like the following

const Root = StackNavigator({
Auth: { screen: AuthStack },
Main: { screen: MainStack },
Menu: { screen: MenuStack },
});

Next, we also have Nested Stacks that have been called on MainNavigator

const AuthStack = StackNavigator({
AuthOne: { screen: AuthOne },
AuthTwo: { screen: AuthTwo },
...
});
const MainStack = StackNavigator({
MainOne: { screen: MainOne },
MainTwo: { screen: MainTwo },
...
});
const MenuStack = TabNavigator({
MenuOne: { screen: MenuOne },
MenuTwo: { screen: MenuTwo },
...
});

When we run the React Native app, by default the initial route will be Auth → AuthOne. If we navigate to AuthTwo, we can still do. Because Auth has Nested Stacks it consists of AuthOne and AuthTwo. But if we navigate to Main then it will appear Error: There is no route defined for key Main. Must be one of ‘AuthOne’,’AuthTwo’. Because we’re on route Auth.

Solution

Source: http://kapsulbioenergi.com/

To resolve the issue. Usually I do a reset stack

import { StackActions, NavigationActions } from 'react-navigation';
const resetAction = StackActions.reset({
index: 0,
key: null,
actions: [
NavigationActions.navigate({ routeName: 'Main' })
],
});
this.props.navigation.dispatch(resetAction);

Adding key: null means master route will be null and not on any route. So we are free to navigate to the route in any Nested Stacks.

Reference: https://reactnavigation.org/docs/navigation-actions.html#reset

That it all and thank you. Hope can be useful :)

Write the topic idea or request topic you are currently learning about React Native. Contribute your idea or request here http://bit.ly/RequestTopicReactNative

--

--

Garry Priambudi
React Native Zone - English

CTO as a services, Product Manager with Fullstack Background, Geeks. Father and Husband with love.