Logout using react Native DrawerNavigator
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;
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'
}
);
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'
},
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:
- In 4.x version of react-navigation you should import `import {DrawerNavigatorItems} from 'react-navigation-drawer'
- You should import SafeAreaView from 'react-native-safe-area-view'