Search code examples
javascriptreact-nativereact-navigation-v5

With React Navigation 5, how do I make navigating to a drawer item reset the state of that stack?


I am using React Navigation v5 and have a drawer navigator whose screens are a bunch of stack navigators.

    <AppDrawer.Navigator drawerContent={({navigation, state}) => <DrawerScreen navigation={navigation} state={state}/>}>
      <AppDrawer.Screen name="TodayStack" component={TodayStackComponent}/>
      <AppDrawer.Screen name="ClientsStack" component={ClientsStackComponent}/>
      <AppDrawer.Screen name="SettingsStack" component={SettingsStackComponent}/>
    </AppDrawer.Navigator>

In DrawerScreen (which is my custom override of the Drawer component), I have it currently navigating to each drawer item like this:

props.navigator.navigate('TodayStack')

That works fine in general. However, I also want it to reset the stack state when you navigate from the drawer. For example, I may have 3 stacked screens in the navigation history of TodayStack. When I go to another drawer item, then tap back to TodayStack, I want it to reset back to the initial route for TodayStack's navigator.

Any tips on how to do this?


Solution

  • try the following:

    import { CommonActions, useNavigation } from '@react-navigation/native';

    then replace your code:

    props.navigator.navigate('TodayStack')
    

    with

    navigation.dispatch(
      CommonActions.reset({
        index: 0,
        routes: [
          { name: 'TodayStack' },
        ],
      })
    );