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

Cannot navigate to route from within navigation stack.


I have one file with my whole navigation stack. In my navigation header I have a menu and I want to open a Drawer. Now In this example I get the error: Cannot read property 'navigation' of undefined

My AppNavigation file:

import React from 'react';
import { Text } from 'react-native';
import { createStackNavigator, createDrawerNavigator } from 'react-navigation';
import  Login from '../components/Login';
import Dashboard from '../components/Dashboard';
import NewNotification from '../components/NewNotification';


const GuestStack = createStackNavigator(
  {
    loginScreen: { screen: Login },
  }, { 
    headerMode: 'float',
    headerLayoutPreset: 'center',
    navigationOptions: {
      headerStyle: { backgroundColor: '#61b1cd' },
      title: 'Welcome',
      headerTintColor: 'black',
    },
  },
);

const LoggedinStack = createDrawerNavigator({
  dashboard: { screen: Dashboard },
  newNotifciation: { screen: NewNotification },
});

const LoggedinNavigation = createStackNavigator(
  {
    LoggedinStack: { screen: LoggedinStack },
  }, {
    headerMode: 'float',
    navigationOptions: {
      headerStyle: { backgroundColor: '#61b1cd' },
      title: 'Welkom!',
      headerTintColor: 'black',
      headerLeft: <Text onPress = { () =>
        this.props.navigation.openDrawer('dashboard')
//  navigation.openDrawer('dashboard')
       }>Menu</Text>,
    },
  },
);

const VveNavigator = createStackNavigator(
  {
    guestStack: {
      screen: GuestStack,
    },
    loggedinStack: {
      screen: LoggedinNavigation,
    },
  }, {
    headerMode: 'none',
    initialRouteName: 'guestStack',
  },
);

export default AppNavigator;

The problem seems to be over here:

headerLeft: <Text onPress = { () =>
            this.props.navigation.openDrawer('dashboard')
    //  navigation.openDrawer('dashboard')
           }>Menu</Text>,

And then in my App.js I have

export default class App extends React.Component {
  render() {
    return (
      <APPNavigator />
    );
  }
}

Version of react navigation is 2.18.1

Thanks


Solution

  • headerLeft doesn't receive navigation prop (check the source code). So if you'd like to use a navigation prop on press, you should consider to refactor your stack navigator config:

    const LoggedinNavigation = createStackNavigator(
      {
        LoggedinStack: { screen: LoggedinStack },
      }, {
        headerMode: 'float',
        navigationOptions: ({ navigation }) => ({ // here you get the navigation
          headerStyle: { backgroundColor: '#61b1cd' },
          title: 'Welkom!',
          headerTintColor: 'black',
          headerLeft: (
            <Text
              onPress={() => {
                navigation.openDrawer()
              }}
            >
              Menu
            </Text>
          ),
        }),
      },
    );
    

    Check this issue for more options.