Search code examples
react-nativereact-navigationreact-navigation-stackreact-navigation-drawer

React native nested navigation - go back to initial route of stack navigator when the parent drawer route is clicked


I am using the following navigation setup in my react native project. Here I am using drawer navigation and stack navigation.

import MainScreen from '../components/MainScreen';
import SettingsScreen from '../components/SettingsScreen';
import FriendsListScreen from '../components/FriendsListScreen';
import FriendProfileScreen from '../components/FriendProfileScreen';

// stack navigator - 1
const MainScreenStack = createStackNavigator(
    {
        MainScreen: MainScreen,
        FriendsListScreen: FriendsListScreen,
        FriendProfileScreen: FriendProfileScreen,
    },
    {
        initialRouteName: 'MainScreen',
        navigationOptions: {
            drawerLabel: "Home"
        },
    }
);

// stack navigator - 2
const SettingsScreenStack = createStackNavigator(
    {
        SettingsScreen: SettingsScreen
    },
    {
        navigationOptions: {
            drawerLabel: "Settings"
        },
    }
);

// drawer navigation (stack navigator 1 + 2)
const AppNavigator = DrawerNavigator({
  MainScreen: MainScreenStack,
  SettingsScreen: SettingsScreenStack
});

const AppContainer = createAppContainer(AppNavigator)

Scenario:

  • From the drawer, I am clicking "Home" link and navigating to MainScreen.
  • From the MainScreen, I am clicking a button and navigating to FriendsListScreen.
  • From the FriendsListScreen, I am again opening the drawer and clicking the "Home" link. The drawer closes and no navigation happens.

Mock-up:

enter image description here enter image description here enter image description here

Is there a way to navigate back to the MainScreen when I am clicking "Home" link from the drawer?


Solution

  • I got a workaround for this by creating a custom drawer content as below:

    import {DrawerItems, SafeAreaView, createStackNavigator, createDrawerNavigator, createAppContainer} from "react-navigation";
    
    const DrawerContent = (props) => (
      <ScrollView>
        <SafeAreaView forceInset={{top: 'always', horizontal: 'never'}}>
          <DrawerItems {...props} onItemPress={ ({route, focused}) => {
            if (route.key === "MainScreen") {
              if (route.routes.length === 1) {
                props.navigation.closeDrawer();
              } else {
                props.navigation.navigate(route.routes[0].routeName);
              }
            } else {
              props.onItemPress({route, focused});
            }
          }} />
        </SafeAreaView>
      </ScrollView>
    );
    
    const AppNavigator = DrawerNavigator({
      MainScreen: MainScreenStack,
      SettingsScreen: SettingsScreenStack
    }, {contentComponent: DrawerContent});