React Navigation logout button on TabNavigator

8k views Asked by At

I have a TabNavigator inside a StackNavigator (in the StackNavigator I have the login view and the TabNavigator, which contains the other screens). The problem is that I have to make something like a 'Logout' button on a Tab that just redirect to the Login view. If I try to simply redirect to the LoginView, the TabBar still appearing on the bottom of the screen and that's not what I want. Is there any way to click on the TabBar button and return to the initial StackNavigator? (Like an OnPress property or something like that).

Here is my router

const tab_bar = TabNavigator({
      Home: {
        screen: HomeScreen
      },
      Logout: {
        screen: LoginView  // this just show the view but the tabBar still appearing
      },
    });

const Login = StackNavigator({
  login: {
    screen: LoginView,
  },
  List: {
    screen: tab_bar
    ,navigationOptions: {header:null}
  }
},
{
  initialRouteName: 'login'
});
1

There are 1 answers

1
Jose Vf On BEST ANSWER

Done! Using the tabBarOnPress property and the Navigation Actions.

const tab_bar = TabNavigator({  // This tabNavigator is inside a stackNavigator, wich contains the 'login' view
   Home: {
     screen: Home
   },
   Logout: {
     screen: Logout     // Empty screen, useless in this specific case
       ,navigationOptions: ({navigation}) => ({
           tabBarOnPress: (scene, jumpToIndex) => {
               return Alert.alert(   // Shows up the alert without redirecting anywhere
                   'Confirmation required'
                   ,'Do you really want to logout?'
                   ,[
                     {text: 'Accept', onPress: () => { navigation.dispatch(NavigationActions.navigate({ routeName: 'login' }))}},
                     {text: 'Cancel'}
                    ]
               );
           },
       })
    },
});

When the user clicks the logout button on the tabBar displays an Alert to confirm the action, then if the user accepts redirect to the login view.

NOTE (22/09/2017): To use the tabBarOnPress property download the master branch version (not the version from NPM yet).