Search code examples
react-nativereact-navigation-v5

React Native goBack() with TabNavigator and StackNavigator react-navigation v5


Probably I am not doing well with react navigation and do not understand how nested navigation works. I've got BottomTabNavigator with StackNavigator's in every component like in the example below.

const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();

function AStack(props){
    <Stack.Navigator mode="card" headerMode="screen">
      <Stack.Screen name="FirstScreenA" component={FirstScreenA}/>
      <Stack.Screen
                name="SecondScreenA"
                component={SecondScreenA}
                options={{
                    headerLeft:  () => (
                        <TouchableOpacity
                            onPress={() => props.navigation.goBack()} >
                        </TouchableOpacity>/>
    </Stack.Navigator>



<Tab.Navigator>
  <Tab.Screen name="A" component={AStack} />
  <Tab.Screen name="B" component={BStack} />
</Tab.Navigator>

Inside FirstScreenA component I have button which navigates to SecondScreenA. And by props.navigaton.goBack() in Stack.Screen I want to go back to the FirstScreenA.

In fact, goBack() takes me to the previous screen in terms of Tab.Navigator. So, if I was in the BStack before, goBack() in the AStack moves me to screen in BStack.

My goal is to go back to the previous screen in AStack.

As far as I understand navigation prop from Tab.Navigator automatically goes to Stack Components. In this case I am not able to use anything like pop(), push(), popToTop() methods which should help, because those methods are not available in Tab.Navigator's navigation. Any hooks with StackActions does not work neither. navigation.navigate('FristScreenA') does not work, seems like it is think, that we already in the needed stack and screen, so nothing happens.

I guess there is a way to use internal navigation in Stack (not nested from Tab), but didn't find way to do that. If someone could clarify me and explain what to do - it would be great. Thanks in advance.


Solution

  • This is because you are receiving props.navigation in the stack navigator component AStack, which is the direct children of your TabNavigator. In react navigation, children receive the props.navigation object of their containing parents, in your case, you're reciveing props.navigation object of the TabNavigator, that's why using goBack takes you to the previous Tab of your TabNavigator.

    To receive navigation props of your stack navigator, you need to do that in your Stack.Screen components, in your case in FirstScreenA or SecondScreenA because they're the direct children of your StackNavigator. So using props.navigation.goBack in SecondScreenA component would actually take you back to FirstScreenA.