Search code examples
iosreact-nativereact-native-navigationstack-navigatorreact-navigation-v5

How to do nested navigation in stack navigator from child to another child v5?


I got stuck at a point where i want to do some nested navigation from child screen to another child screen. Below is my required stack navigation.

  Home Screen
     -> Add User
     -> View Users 
          -> No Users(Shown only incase no users found)
          -> Users List(Shown when users Data found)
              ->View Details

Below is the code which i tried to replicate the above stack navigator with nested navigation for ViewUsers. But i was confused in implementing from this https://reactnavigation.org/docs/nesting-navigators/

 const HomeStack = createStackNavigator();
 function UserDetailsRoot(){
 return (
    <HomeStack.Navigator>
        <HomeStack.Screen name="No Users" component={NoUsers} />
        <HomeStack.Screen name="Users List" component={UsersList} />
        <HomeStackScreen  name="User Details" component={UserDetails} />
    </HomeStack.Navigator>

   )
 }
 const HomeStackScreen = () => (
<HomeStack.Navigator>
    <HomeStack.Screen name="Home " component={HomeScreen} />
    <HomeStack.Screen name="Add User" component={AddUsers} />
    <HomeStack.Screen name="UserDetailsRoot" component={UserDetailsRoot} />
</HomeStack.Navigator>

);

export default () => (
<NavigationContainer>
    <HomeStackScreen />
</NavigationContainer>
);

Any help is appreciated. Thanks.


Solution

  • I think you're missing the point of nesting navigators. In your code your nesting a Stack inside a Stack, which I believe isn't correct. What I'd probably do is something like this

    const MainStackScreen = () => (
    <HomeStack.Navigator>
        <HomeStack.Screen name="Home " component={HomeScreen} />
        <HomeStack.Screen name="AddUser" component={AddUsers} />
        <HomeStack.Screen name="UsersList" component={UsersList} />
        <HomeStack.Screen name="UserDetails" component={UserDetails} />
    </HomeStack.Navigator>
    );
    
    export default () => (
    <NavigationContainer>
        <MainStackScreen />
    </NavigationContainer>
    );
    

    You definitely don't need a screen for "no users" state, I assume that in UsersList you're rendering a SectionList or a FlatList, so if your API return empty, you can use ListEmptyComponent to handle that specific case.

    Also nesting navigators is useful when you need to combine features from one navigator with another, for example placing a StackNavigator inside each tab of a TabNavigator is a common pattern. Another case is when you need to render something as a modal over the Stack, in that case you need to add a StackNavigator as a container.

    Hope it'll help you :)