react-nativereact-navigationreact-navigation-stackreact-navigation-drawer

Closing Drawer On Logout in React Native


In my React Native app, I have a StackNavigator that handles the login process and a DrawerNavigator which is available for authenticated users.

When I log out of the app and then log back in, I see that the drawer is still open. When I click to log out, I invoke the handleClickLogOut() function in my Navigator component -- see below. I thought by accessing the MainMenuDrawer, I could access closeDrawer() method but I don't see it there.

How can I close the drawer on log out in this code?

Here's the Navigator component:

const LogInStack = new createStackNavigator();
const MainMenuDrawer = createDrawerNavigator();

class Navigator extends Component {

    constructor(props) {
        super(props);
        this.handleClickLogOut = this.handleClickLogOut.bind(this);
    }

    componentDidMount() {

        if (this.props.isAuthenticatedUser && !this.props.isAuthenticated)
            this.props.actions.setIsAuthenticated(true);
    }

    handleClickLogOut() {

        removeAuthenticationData()
            .then(() => {

                return this.props.actions.setIsAuthenticated(false);
            });
    }

    render() {
        return (
            <NavigationContainer>
                {
                    this.props.isAuthenticated
                    ? <MainMenuDrawer.Navigator drawerContent={(navigation) => <DrawerContent member={this.props.member} navigation={navigation} handleClickLogOut={this.handleClickLogOut} />}>
                        <MainMenuDrawer.Screen name="Home" component={Dashboard} />
                        <MainMenuDrawer.Screen name="ToDoList" component={ToDoList} />
                      </MainMenuDrawer.Navigator>
                    : <LogInStack.Navigator screenOptions={{ headerShown: false }}>
                        <LogInStack.Screen name="LoginScreen" component={Login} />
                      </LogInStack.Navigator>
                }
            </NavigationContainer>
        );
    }
}

Solution

  • @Sam here is the solution brother.

    import {DrawerActions} from '@react-navigation/native'
    

    then you can call in DrawerContent.js file with this:

    navigation.dispatch(DrawerActions.closeDrawer())
    

    Hope this will help you 👐.

    Here is my Real Code in DrawerContent.tsx file

    enter image description here