ronkot
ronkot

Reputation: 6347

How to always push initial screen to stack navigator (react-navigation@5)

I'm building a React Native app using react-navigation (version 5) library to implement navigation.

I have a tab navigator that contains a stack navigator on each tab. Each stack navigator has a "landing page", i.e. the initialRouteName that is shown when tab is activated.

Let's say the structure is:

Tabs
|
+-- Stack1
|     |
|     +-- Stack1LandingPage
|     |
|     +-- Stack1ContentPage
|
+-- Stack2
      |
      +-- Stack2LandingPage
      |
      +-- Stack2ContentPage

Problem is, when I try navigate directly from Stack1LandingPage to Stack2ContentPage, the Stack2 stack is as follows:

Stack2ContentPage

and thus there's no "back" button on header to go back to Stack2LandingPage.

What I'd like to have instead is to always have the landing page on bottom of each stack. So, when I navigate from Stack1LandingPage to Stack2ContentPage, the Stack2 stack would be as follows:

Stack2ContentPage
Stack2LandingPage

How could this be implemented with react-navigation version 5?

Upvotes: 4

Views: 3596

Answers (2)

Acheme Paul
Acheme Paul

Reputation: 1275

Another option is to clear the stack of the navigation before navigating, so when you return to that navigation, the navigation starts from the top

      navigation.dispatch(StackActions.popToTop());
      navigation.navigate("NextScreen");

Upvotes: 2

Syed SaeedulHassan Ali
Syed SaeedulHassan Ali

Reputation: 594

If you need to render the initial route specified in the navigator, you can disable the behaviour of using the specified screen as the initial screen by setting initial: false:

navigation.navigate('Root', {
  screen: 'Settings',
  initial: false,
});

ref: https://reactnavigation.org/docs/nesting-navigators/#rendering-initial-route-defined-in-the-navigator

Upvotes: 13

Related Questions