HB.K
HB.K

Reputation: 177

How to reset a specific stack navigator from outside of it?

I'm making an app using react-navigation with react-native.

The structure of my app is,

Main Tab
  - Tab 1 (Stack)
    - screen A
    - screen B
    - screen C
  - Tab 2 (Stack)
    - screen D
    - screen E
    - screen F

What I want to do is reset Tab 1 (Stack Navigator) at the specific time and do not navigate to Tab 1.

if a user is located in screen F, I just want to reset Tab 1 (Stack) without letting the user move to Tab 1.

So I think dispatching navigation actions should be triggered outside of these react components, somewhere like resetHelper.js

But I can't figure out how to reset a specific stack without navigating that stack.

Any help would be appreciated. Thanks in advance!

Upvotes: 0

Views: 584

Answers (1)

thecodrr
thecodrr

Reputation: 275

Normally, if you were in a specific stack, you would reset via this.props.navigation.reset() but since you want to reset one stack from another stack you will need to use a NavigationService for the StackNavigator that needs to be reset.

Read this help guide to see how you can create a NavigationService.

Once you have a NavigationService setup, edit the NavigationService.js to this:

import { StackActions, NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function reset(index = 0, actions) {
  _navigator.dispatch(
    StackActions.reset({
      index,
      actions
    })
  );
}

// add other navigation functions that you need and export them

export default {
  reset,
  setTopLevelNavigator,
};

Then from any function in any file, do this:

import {reset} from NavigationService.js
//your other code and functions here.
reset(0, actions)

Read more about it here.

Upvotes: 1

Related Questions