Set 'back' action to the previous screen after navigating between nested stacks

Viewed 119

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"

1 Answers

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
Related