I am having a hard time understanding how the back-button is supposed to work with @react-navigation/stack
(version 5). The problem I am facing is: when I am in a deep nested screen and press the back button, it takes me straight to the top screen of my app and not the immediate previous step.
First let me illustration the (over-simplified) structure of my navigators and screens. Then I will display the code used to implement it.
- RootNavigator
- HomeScreen
- TicketNavigator:
- CreateTicket screen
- TakeTicketPicture screen
So when the app starts, it lands on the home screen (RootNavigator-HomeScreen
). And here the header bar title is "Home".
From here, clicking a button, user is taken to the TicketNavigator-CreateTicket
(Notice that now I am in a nested stack navigator). Header bar title is now "Create ticket". From this point, user moves to the TakeTicketPicture
screen (!! header bar title not changing). If user clicks back-button
from this screen, he is taken back directly to the home screen, not the previous screen (within the same nested navigator).
Here is the code (simplified):
root-navigator.tsx
...
import { CreateTicketNavigator } from './create-ticket-navigator';
<Stack.Navigator>
<Stack.Screen name='Home' component={HomeScreen}/>
<Stack.Screen name='CreateTicket' component={CreateTicketNavigator} />
</Stack.Navigator>
create-ticket-navigator.tsx
<Stack.Navigator>
<Stack.Screen name='CreateTicketScreen' options={{headerShown: false}} component={CreateTicketScreen} /> {/** headers are hidden in nested navs */}
<Stack.Screen name='TakePictureScreen' options={{headerShown: false}} component={TakePictureScreen} />
</Stack.Navigator>
The weird think is that if I allow nested navs to have headers, then I seen "duplicated" headers in my screen, one for each stack navigator. In this case when I click the "nested back-button", I navigate back to the initial screen of the "nested navigator" (which is the behaviour I am looking for).
Obviously I have to hide the second navigator. But it seems that the "outer" header bar is only connected to the to level stack navigator. To solve this problem, I get rid of the nested stack navigator and put all my screens on the same level (siblings).
Is it a bad practice to nest stack navigators? How to make the back button (or the header bar) to reflect the navigation when user in within nested navigator?