react-nativereact-navigationreact-navigation-drawer

Navigation drawer is not opening and toggleDrawer not found


Trying to create drawer using React-Navigation.

Using React Native 0.59, Installed React-Navigation 3.x, has done linking react-native link react-native-gesture-handler.

Create routes using React-Navigation, called Route.js:

const Drawer = createDrawerNavigator(
  {
    Settings: {
      screen: HomeScene,
      navigationOptions: {
        title: 'Home',
        drawerIcon: () => (
          <Icon name="home" style={{ color: colors.white, fontSize: 24 }} type="Ionicons" />
        )
      }
    }
  },
  {
    contentComponent: props => <GlobalSideMenu {...props} />
  }
);

const AppNavigator = createStackNavigator(
  {
    Home: {
      screen: HomeScene,
      navigationOptions: {
        header: null
      }
    },
    Drawer: {
      screen: Drawer,
      navigationOptions: {
        header: null
      }
    }
  },
  {
    initialRouteName: 'Home'
  }
);

export default createAppContainer(AppNavigator);

Then in the header, drawer icon:

 <Button icon transparent onPress={() => this.props.navigation.toggleDrawer()}>
      <Icon name={icon('menu')} type="Ionicons" style={styles.menuColor} />
 </Button>

It gives me error : toggleDrawer() is undefined.

Then I change it to :

this.props.navigation.dispatch(DrawerActions.toggleDrawer());

Now, there is no error, but the drawer is not opening.


Solution

  • This is usually the case if you are attempting to open the drawer from outside the drawer navigator's set of screens.

    this.props.navigation.toggleDrawer is only defined if you are in Settings, which I guess is not the case.

    You can either rearrange the navigation so that the drawer is present on the screen you are calling toggleDrawer from, or you can navigate to Settings first.

    <Button
      icon 
      transparent 
      onPress={() => {
        this.props.navigation.navigate('Settings');
        this.props.navigation.dispatch(DrawerActions.openDrawer());
      }}
    >
      <Icon name={icon('menu')} type="Ionicons" style={styles.menuColor} />
    </Button>
    

    Here is an example to clarify.