Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Logout inside a DrawerNavigator

I want to navigate back from DrawerNav to Login. Using alert('Alert') inside the function is OK.

I have a StackNavigator with Login and DrawerNav

const MyStackNavigator = StackNavigator({
  Login : { screen : Login },
  DrawerNav : { screen : DrawerNav }
  }, {
    navigationOptions : { header : false }
  }
);

From Login i can navigate to my main screen DrawerNav using

_login = () => {
  this.props.navigation.navigate('DrawerNav');
}

Inside the DrawerNav is a DrawerNavigator (obviously)

const MyDrawerNavigator = DrawerNavigator({
    ... screens ...
  }, {
    initialRouteName : '',
    contentComponent : CustomContent,
    drawerOpenRoute : 'DrawerOpen',
    drawerCloseRoute : 'DrawerClose',
    drawerToggleRoute : 'DrawerToggle'
  }
);

const CustomContent = (props) => (
    <View>
      <DrawerItems {...props} />
      <TouchableOpacity
        onPress={ this._logout }>
        <Text style={ styles.logout }>Logout</Text>
      </TouchableOpacity>
   </View>
)

As you can see, the logout is not part of the menu but inside the Drawer

_logout = () => {
  this.props.navigation.navigate('Login');
}

This gives me an error

undefined is not an object (evaluating '_this.props.navigation')
like image 826
Maki Avatar asked Mar 18 '18 12:03

Maki


1 Answers

As you are quite deep in your navigation stack wouldn't it make sense to use the popToTop function?

In the same file make sure that you define your _logout function as your CustomContent, then you could do something like the following:

  1. Update the function call by passing props to them
  2. Update _logout to use popToTop()

Here is how my code would look.

_logout = (props) => {
  props.navigation.popToTop();
}

const CustomContent = (props) => (
    <View>
      <DrawerItems {...props} />
      <TouchableOpacity
        onPress={ () => this._logout(props) }>
        <Text style={ styles.logout }>Logout</Text>
      </TouchableOpacity>
   </View>
)

You will want to pass the props to the function as that will contain your navigation prop and allow you to make calls on your navigation stack.

like image 70
Andrew Avatar answered Nov 07 '22 17:11

Andrew