Gouranga Panigrahi
Gouranga Panigrahi

Reputation: 113

Logout using react Native DrawerNavigator

I am building a react-native app(App Image)which has Logout link on the Drawer Navigator.

Code is as below

 const DrawerScreen = DrawerNavigator({
    ..........
    logout: {
        screen: Component   
    },
})

export default DrawerScreen;

But the problem is , it's only loading the component screen. i need to call a method where i can perform Asyncstorage clear and navigate to LoginPage.

Upvotes: 11

Views: 24657

Answers (8)

Maitri Shah
Maitri Shah

Reputation: 11

Here is a way to implement a logout in a drawer using a react-navigation library.

<Drawer.Screen
    name="Logout"
    component={<Any Dummy Component>}
    listeners={({ navigation }) => ({ 
        state: (e) => {
           if (e.data.state.index === 3) {
              // 3 is index of logout item in drawer

              navigation.replace("Login")
           }
        }
    })}
/>

Upvotes: 0

Sanchitos
Sanchitos

Reputation: 8591

In case you are looking for an answer in navigation version 5 and funcional components:

  const getActiveRouteState = function (
    routes: Route<string>[],
    index: number,
    name: string
  ) {
    return routes[index].name.toLowerCase().indexOf(name.toLowerCase()) >= 0;
  };

function CustomDrawerContent(
    props: DrawerContentComponentProps<DrawerContentOptions>
  ) {
    return (
      <View style={{ flex: 1 }}>
        <DrawerContentScrollView {...props}>
          <View>
            <DrawerItem
              icon={({ color, size }) => <Icon type='AntDesign' name='home' />}
              label='Home'
              focused={getActiveRouteState(
                props.state.routes,
                props.state.index,
                'Home'
              )}
              onPress={() => {
                props.navigation.navigate('Home');
              }}
            />
            <DrawerItem
              icon={({ color, size }) => (
                <Icon type='AntDesign' name='minuscircle' />
              )}
              label='Test'
              focused={getActiveRouteState(
                props.state.routes,
                props.state.index,
                'Test'
              )}
              onPress={() => {
                props.navigation.navigate('Test');
              }}
            />
            <DrawerItem
              icon={({ color, size }) => (
                <Icon type='AntDesign' name='logout' />
              )}
              label='LogOut'
              onPress={async () => {
                await logoutUser();
                setLogginState(false);
              }}
            />
          </View>
        </DrawerContentScrollView>
      </View>
    );
  }

      const AppDrawer = createDrawerNavigator();
      const AppDrawerScreen = () => (
        <AppDrawer.Navigator
          drawerPosition='left'
          drawerContent={(props) => <CustomDrawerContent {...props} />}
        >
          <AppDrawer.Screen
            name='Home'
            component={HomeScreen}
            options={{ drawerLabel: 'Home' }}
          />
          <AppDrawer.Screen name='Test' component={TestScreen} />
        </AppDrawer.Navigator>
      );

This will also help you in case you want to hide an option in the drawer.

Upvotes: 2

Keshav Gera
Keshav Gera

Reputation: 11244

import {StyleSheet,AsyncStorage,Alert, View,SafeAreaView, Text, ActivityIndicator, Dimensions, TextInput,Image, TouchableOpacity, TouchableHighlight} from 'react-native';
import {DrawerItems,DrawerActions} from 'react-navigation-drawer';

 {
            contentComponent:(props) => (
              <View style={{flex:1}}>
                <SideMenu {...props}/>
                    <DrawerItems {...props} />
                    <TouchableOpacity onPress={()=>
                      Alert.alert(
                        'Log out',
                        'Do you want to logout?',
                        [
                          {text: 'Cancel', onPress: () => {this.props.navigation.dispatch(DrawerActions.closeDrawer()) }},
                          {text: 'Confirm', onPress: () => {
                            AsyncStorage.clear();
                            props.navigation.navigate('LoginScreen')
                          }},
                        ],
                        { cancelable: false }
                      )
                    }>
                      <Text style={{margin: 16,fontWeight: 'bold',color: 'red'}}>Logout</Text>
                    </TouchableOpacity>
              </View>
            ),
            drawerOpenRoute: 'DrawerOpen',
            drawerCloseRoute: 'DrawerClose',
            drawerToggleRoute: 'DrawerToggle'
    },

Upvotes: 2

Bright Lee
Bright Lee

Reputation: 2326

You probably want to add a button to your drawer. If so, your code will look like this.

const Drawer = DrawerNavigator(
{
    mainpage:{screen:MyScreen}
},
{
    contentComponent:(props) => (
        <View style={{flex:1}}>
            <SafeAreaView forceInset={{ top: 'always', horizontal: 'never' }}>
                <DrawerItems {...props} />
                <Button title="Logout" onPress={DO_SOMETHING_HERE}/>
            </SafeAreaView>
        </View>
    ),
    drawerOpenRoute: 'DrawerOpen',
    drawerCloseRoute: 'DrawerClose',
    drawerToggleRoute: 'DrawerToggle'
})

You should import import {DrawerItems} from 'react-navigation'; to get it work.

UPDATE:

  1. In 4.x version of react-navigation you should import `import {DrawerNavigatorItems} from 'react-navigation-drawer'
  2. You should import SafeAreaView from 'react-native-safe-area-view'

Upvotes: 22

Bennet roy
Bennet roy

Reputation: 121

const DrawerNavigation = createDrawerNavigator(
  {
    Mainpage: {
      screen: Mainpage
    }
  },
  {
    contentComponent:(props) => (
      <View style={{flex:1}}>
          <SafeAreaView forceInset={{ top: 'always', horizontal: 'never' }}>
            <DrawerItems {...props} />
            <TouchableOpacity onPress={()=>
              Alert.alert(
                'Log out',
                'Do you want to logout?',
                [
                  {text: 'Cancel', onPress: () => {return null}},
                  {text: 'Confirm', onPress: () => {
                    AsyncStorage.clear();
                    props.navigation.navigate('Login')
                  }},
                ],
                { cancelable: false }
              )  
            }>
              <Text style={{margin: 16,fontWeight: 'bold',color: colors.textColor}}>Logout</Text>
            </TouchableOpacity>
          </SafeAreaView>
      </View>
    ),
    drawerOpenRoute: 'DrawerOpen',
    drawerCloseRoute: 'DrawerClose',
    drawerToggleRoute: 'DrawerToggle'
  }
);

Upvotes: 10

kunal pal
kunal pal

Reputation: 324

Just use AlertView bro that will help but in the above example if you have an header than this (this.props.navigation.navigate('LoginPage'))

will not make any senses

your view will load below the header

Upvotes: 0

You can create a modal which will do this for you. On click of logout -> display modal using visible attribute and on click of yes then close the modal -> navigate to login screen.

Upvotes: 0

mefallit
mefallit

Reputation: 106

You can use Component class for perform Asyncstorage clear and navigate Login Page. If you use react-navigation this.props has navigation object.

class YourComponent extends Component {
    constructor(props) {
        super(props);
     }

    componentWillMount() {
        Asyncstorage.clear();
        this.props.navigation.navigate('LoginPage')
    }
}
export default YourComponent;

Upvotes: 2

Related Questions