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

React-navigation drawer is routing me back to previous screen immediately after rendering item screen


I have a StackNavigation like this:

const AppNavigator = createStackNavigator({

Login: {
    screen: Login,
    navigationOptions: () => ({
        title: 'Login',
        headerTintColor: 'white',
        headerStyle:{
            backgroundColor: '#000',
            elevation: 0,
            showdowOpacity: 0
        },
    })
},

Home: {
    screen: AppDrawerNavigator,
    navigationOptions: () => ({
        header: null
    })
},
});

With a DrawerNavigator nested inside:

const AppDrawerNavigator = createDrawerNavigator({

Home: {
    screen: Home,
    navigationOptions: {
        drawerLabel: 'Home',
        gesturesEnabled: false,
    }
},

Favorites: {
    screen: Favorites,
    navigationOptions: {
        drawerLabel: 'Favorites',

    }
}

},
{
    drawerPosition: 'left',
    contentComponent: props => <Drawer {...props} />
});

The initial route of the stack navigator is working fine

Login -> Home

But when I try navigating from Home to Favorites it navigates immediately back to Home after rendering the Favorites screen.

I am using [email protected] and [email protected]


Solution

  • With Home being used in both stack and drawer navigator. There are high chances of name conflicts occurring here.

    Try this structure.

    const Stack = {
        FirstView: {
            screen: FirstView
        },
        SecondView: {
            screen: SecondView
        },
        ThirdView: {
            screen: ThirdView
        }
    };
    
    const DrawerRoutes = {
        FirstViewStack: {
            name: 'FirstViewStack',
            screen: StackNavigator(Stack, { initialRouteName: 'FirstView' })
        },
        SecondViewStack: {
            name: 'SecondViewStack',
            screen: StackNavigator(Stack, { initialRouteName: 'SecondView' })
        },
        ThirdViewStack: {
            name: 'ThirdViewStack',
            screen: StackNavigator(Stack, { initialRouteName: 'ThirdView' })
        },
    };
    
    const RootNavigator =
        StackNavigator({
            Drawer: {
                name: 'Drawer',
                screen: DrawerNavigator(
                    DrawerRoutes,
                ),
            },
            ...Stack
        },
            {
                headerMode: 'none'
            }
        );
    

    I faced a similar issue when i tried to use a hamburger menu in my Home page (which uses stack navigator to goto other pages).

    Check this Git Article also.