4

Given two stacks:

Parent Stack
 - Stack A
       First
       Second
 - Stack B
       One
       Two

I need to navigate from First to One. This question and this documentation let me do that:

 navigation.navigate('Stack B', {
        screen: 'One'
     }
)

Now that I'm on One, I want the 'Back' button to send me back to the previous screen (First). However, the back button sends me to the top of the current stack (Stack B), not the previous screen.

I can fix this by passing the current screen and some data as parameters in the navigate call, and then doing something to the header in One, something like:

// Navigate from First --> One
 navigation.navigate('Stack B', {
        screen: 'One',
        params: {
             screenToGoBackTo: {
                 name: 'First', 
                 parent: 'Stack A'
             }
        }}
);

and then set the header back-button in One by constructing the backwards navigation path:

// Call this from the header back button. 
// Also set the header back button title from props.screenToGoBackTo.name. 

navigation.navigate(props.screenToGoBackTo.parent, { props.screenToGoBackTo.name });   

but this is complex and fragile (screens can't be moved within the stacks at a later date).

Is there a simple way to set the 'back' behaviour (and title!) after navigating through nested navigators?

Edit: I'm using "@react-navigation/native": "^5.6.0"

simont
  • 68,704
  • 18
  • 117
  • 136
  • which version of `react-navigation` do you use? – Hagai Harari Jul 03 '20 at 04:47
  • @HagaiHarari I'm using 5.6. – simont Jul 03 '20 at 04:50
  • React navigation suggests not to perceive navigation as a way of 'organizing' your code. If i were you i would 'ask myself' do i need 2 stacks? maybe i only need one stack actually. I dont realy know full ins and outs of your application, but using only one stack in problem you described would actually be the simplest solution. – Andris Laduzans Jul 03 '20 at 08:19
  • I've faced the same problem, and fixed it by passing a backlink param in navigate() like you did. It's not the best practice, but managed to fix the bugs it created along the way and client was satisfied with the result. – Václav Ryska May 19 '21 at 13:31

1 Answers1

0

I think like @Andris Ladizans said, first you might have to check whether you really need two stacks or not. If yes, then one of the solutions might be adding the required screens in multiple stacks (with different name). I'm not sure if this is the right(optimal) thing to do but yes, I've been doing it this way in one of my project(which uses react-navigation v3.x) and it works. So, in your case your stacks would look something like this:

Parent Stack
 - Stack A
       First
       Second
       OneA
 - Stack B
       OneB
       Two
Niraj Niroula
  • 2,376
  • 1
  • 17
  • 36