Home > database >  React Navigation, navigate out of a nested navigator
React Navigation, navigate out of a nested navigator

Time:02-28

I have navigator (X) which holds a screen, lets call it N, and another navigator, Y. I need to travel from a screen in navigator Y, to screen N in the root navigator. How would I go about doing this using react navigation 6?

Code for the root router:

<NavigationContainer>
  <Tabs.Navigator>
    <Tabs.Screen component={HomeRouter} name="HomeTab" />
  </Tabs.Navigator>
</NavigationContainer>

Code for Home router (Navigator X):

<NavigationContainer independent={true}>
  <Stack.Navigator initialRouteName={"Home"}>
    <Stack.Screen name="Home" component={Home} />
    <Stack.Screen name="Post" component={Post} />
    <Stack.Screen name="Profile" component={Account} />
  </Stack.Navigator>
</NavigationContainer>

Code for profile router (Navigator Y):

<NavigationContainer independent={true} theme={MyTheme}>
  <Stack.Navigator>
    <Stack.Screen name="MainProfile" component={MainAccountPage} />
  </Stack.Navigator>
</NavigationContainer>

I need to navigate from the MainAccountPage screen in navigator Y to the Post screen in navigator X.

CodePudding user response:

First of all you should have one single NavigationContainer for all your nested navigators, which means the Y navigator should be like this instead :

<Stack.Navigator>
  <Stack.Screen name="MainProfile" component={MainAccountPage} />
</Stack.Navigator>

After that, as MainAccountPage is used as a screen, you get the navigation object from React Navigation in the props. You could navigate this way (put the line where you need):

export default function MainAccountPage({navigation}){
  navigation.navigate("Post"); // how you navigate
  return <></>
}

And here is a general overview. Say we have those nested navigators:

function Home() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Feed" component={Feed} />
      <Tab.Screen name="Messages" component={Messages} />
    </Tab.Navigator>
  );
}

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Home"
          component={Home}
          options={{ headerShown: false }}
        />
        <Stack.Screen name="Profile" component={Profile} />
        <Stack.Screen name="Settings" component={Settings} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

If you're calling navigation.goBack() in a nested screen, it'll only go back in the parent navigator if you're already on the first screen of the navigator. Other actions such as navigate work similarly, i.e. navigation will happen in the nested navigator and if the nested navigator couldn't handle it, then the parent navigator will try to handle it.

In the above example, when calling navigate('Messages'), inside Feed screen, the nested tab navigator will handle it, but if you call navigate('Settings'), the parent stack navigator will handle it.

  • Related