react native drawer toggle is not working

Viewed 6231

The drawerNavigator is in the stackNavigator.

I set the header to none, and I want to make the header part work when I press the button.

I wrote the following code.

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

No error occurs. But it does not do anything.

The navigator code looks like this:

navigator.js

const MainScene = createStackNavigator({
 MainTab: {screen: MainTab},
 OtherScene: {screen: OtherScene}
},{...})

const OtherScene: createStackNavigator({
 DrawerScene: {screen: DrawerScene}
},{...})

const DrawerScene = createDrawerNavigator({
 Page1: {screen: Page1},
 Page2: {screen: Page2},
},{...})

Header.js

_sideMenu() {
 this.props.navigation.dispatch(DrawerActions.toggleDrawer());
}

render() {
  return (
   ...
   <TouchableOpacity 
    onPress={() => this._sideMenu()}>
    <Image ... />
   </TouchableOpacity>
   ...
  )
 }

Both page1 and page2 contain directly written headers.

Page1.js

render() {
 return(
  <View>
   <Header navigation={this.props.navigation} />
   ...
  </View>
 )
}
2 Answers

try this import { DrawerActions } from "react-navigation";

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

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

One solution for this is to put the stackNavigator inside the drawerNavigation like so:

const MainScene = createStackNavigator({
 MainTab: {screen: MainTab},
 OtherScene: {screen: OtherScene}
},{...})

const OtherScene: createStackNavigator({
 SomeOtherScene: {screen: SomeOtherScene} // remove the drawer from here
},{...})

const DrawerScene = createDrawerNavigator({
 Page1: {screen: Page1},
 Page2: {screen: Page2},
 MainScene: {
     screen: MainScene, 
     navigationOptions: {
         drawerLabel: () => null
    }},
 OtherScene: {
     screen: OtherScene, 
     navigationOptions: {
         drawerLabel: () => null
    }},
},{initialRoute: "MainScene"})

This way you won't have issues with the open/close/toggleDrawer functions being undefined and you can even use them like so: this.props.navigation.toggleDrawer();

If you don't want your "MainScene" and your "OtherScene" to appear in the drawer items just return null for their drawerLabels

Related