Asleepace
Asleepace

Reputation: 3745

How to reset to a different stack with react-navigation

We are using react-navigation as the default navigation system in our react native app, which currently has multiple stacks. We would like to navigate from a screen in one stack to a screen in another stack. This is a basic example of the different stacks:

const StackNavigator = createStackNavigator({
  SplashScreen: connectToStore(SplashScreen),
},{
  initialRouteName: 'SplashScreen',
  mode: 'card'
})

const ModalNavigator = createStackNavigator({
  LoginScreen: connectToStore(LoginScreen),
})

const AppNavigator = createStackNavigator({
  StackNavigator: StackNavigator,
  ModalNavigator: ModalNavigator,
}, {
  initialRouteName: 'StackNavigator',
  headerMode: 'none',
  mode: 'modal'
})

The problem is if we try to reset to a new screen like so:

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

We get an error that says something like so:

ExceptionsManager.js:74 Error: There is no route defined for key DashboardScreen. Must be one of: 'StackNavigator','ModalNavigator'

Upvotes: 4

Views: 3518

Answers (1)

Asleepace
Asleepace

Reputation: 3745

Since this question doesn't seem well documented or answered other places here it is

const resetAction = StackActions.reset({
  index: 0,
  key: null,
  actions: [
    NavigationActions.navigate({
      routeName: 'ModalNavigator',
      action: NavigationActions.navigate({
        routeName:'LoginScreen', 
        params:{}
      })
    })
  ]
});
this.props.navigation.dispatch(resetAction);

First we need to specify the correct stack we want to resetTo in this case the ModalNavigator and then we add a sub-action where we can specify the screen of that navigator ie LoginScreen.

And just for future reference, to pop or go back we can use

this.props.navigation.dispatch(StackActions.pop({ n:1 }));

where n is the number of screens to pop, or just to go all the way:

this.props.navigation.dispatch(StackActions.popToTop());

Upvotes: 2

Related Questions