Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset a Stack in a different Tab using React Navigation 5.x

My app has a TabNavigator with a StackNavigator in each Tab. I'm not resetting the stacks when navigating between them by clicking on different tabs, so when you change tab, the stack contains the previous state. However, occasionally from within a Screen in one Tab, I want to navigate to a specific Screen in a different tab, and on that occasion, I want to reset the stack in the target Tab.

TabNavigator
    Tab1 
      StackNavigator
         - ScreenA
         - ScreenB
    Tab2
      StackNavigator
         - Screen1
         - Screen2

I want to be able to put a button on Screen2 that resets the Stack on Tab1.

I was wondering if the "target" parameter mentioned in the docs here might help, but there's no examples of how to use it. https://reactnavigation.org/docs/navigation-actions/

(I have searched on here but answers suggested for 4.x don't seem to apply anymore). Thanks!

like image 652
anorakgirl Avatar asked Apr 07 '20 20:04

anorakgirl


People also ask

How do you reset the stack in react navigation 5?

To reset the navigation stack for the home screen with React Navigation and React Native, we can use the navigation. dispatch and the CommonActions. reset methods. import { CommonActions } from "@react-navigation/native"; navigation.

How do I reset my tab navigation?

first time screen init TabA ,user click TabB >> TabB has button click to PageA >> PageB >> PageC ,PageC has a button to reset to Tab. let resetAction = NavigationActions. reset({ index: 0, actions: [ NavigationActions. init({routeName: 'Tab'}), ] }); this.

What does the reset method of stack action do?

The reset action wipes the whole navigation state and replaces it with the result of several actions. index - number - required - Index of the active route on routes array in navigation state . actions - array - required - Array of Navigation Actions that will replace the navigation state.


1 Answers

In the end I was able to use the reset action to do this. I dispatched nested state for the tab I wanted to reset:

navigation.dispatch(
  CommonActions.reset({
    routes: [
      {
        name: 'tab-route-name',
        state: {
          routes: [
            { name: 'stack-route-1' },
            { name: 'stack-route-2' },
            { name: 'stack-route-3' }
          ]
        }
      }
    ]
  })
)

It seems to be clever enough that as long as the tab navigator is a parent of the current route, it will find it and reset it.

like image 77
anorakgirl Avatar answered Nov 15 '22 14:11

anorakgirl