Search code examples
react-nativereact-navigationreact-navigation-stackreact-navigation-drawer

React Navigation 4: reset StackNavigator nested inside DrawerNavigator


I am having a common issue with my React Navigation setup.

I have multiple StackNavigator nested in a DrawerNavigator which is inside a SwitchNavigator. Yeah, it's a mess.

Let's say I have a DrawerNavigator with 3 stacks: HomeStack (Home route, Profile route, History route), SearchStack (List route, Detail route) and CartStack (Review route, PaymentMethod route, Confirmation route).

If a user navigates the home stack (Home -> profile -> history) and then goes to SearchStack which naturally leads to CartStack, if I try to take the user to the HomeStack, the navigator takes him to the top screen of the stack (which is history, in this example).

This is a problem when the user tries to navigate using the drawer, because the navigator always takes the user to the top screen on the stack. This might be a natural behavior, but is there a way to override it or reset the stack every time the user press a drawer item? which is the best approach?

I tried using StackActions to take the user from Confirmation route to Home but I get an error ("There is no route defined for...").

--

Main Navigation is this (no problem here switching between screens):

const AppContainer = createAppContainer(
  createSwitchNavigator(
    {
      AuthLoading: LoadingScreen,
      AuthStack: AuthNavigation,
      CoachApp: CoachNavigation,
      StudentApp: StudentNavigation
    },
    {
      initialRouteName: 'AuthLoading'
    }
  )
);

CoachNavigation looks something like this:

export default CoachNavigation = createDrawerNavigator(
  {
    DrawerHome: { screen: HomeStack }, 
    DrawerSearch: { screen: SearchStack }, 
    DrawerCart: { screen: CartStack },
  }
)

Any advice would be helpful. Thanks in advance, sorry if my explanation is not good.


Solution

  • I had to replace the drawer content / items with custom buttons with onpress => navigate('parent stack').

    https://reactnavigation.org/docs/drawer-navigator/#drawercontent