React Navigation : Open drawer when I click on bottom tab navigator

Viewed 3065

With React Navigation 5, I want to open Drawer when I click on bottom tab navigator (I use material bottom navigator).

I manage to create the bottom tabs buttons and click on them, the home page opens for both tabs (GymIndexScreen or FoodIndexScreen).

When I am on the home pages (GymIndexScreen or FoodIndexScreen), I can open the different Drawers with my fingers (GymDrawerNavigator and FoodDrawerNavigator ) : everything works fine.

enter image description here

Question : I want the drawers to open / close (toggle) automatically when I click the bottom tabs buttons, without having to open them with my fingers.

App.js :

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

const App = () => {
  return (
    <NavigationContainer>
      <BottomTabNavigator />
    </NavigationContainer>
  )
}

BottomTabNavigator.js :

import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs'

const Tab = createMaterialBottomTabNavigator()

const BottomTabNavigator = (props) => {
  return (
    <Tab.Navigator>
      <Tab.Screen
        name="Gym"
        component={GymDrawerNavigator}
        options={{
          tabBarLabel: "Musculation",
        )}
      />
      <Tab.Screen
        name="Food"
        component={FoodDrawerNavigator}
        options={{
          tabBarLabel: "Alimentation",
        )}
      />
    </Tab.Navigator>
  )
}

GymDrawerNavigator.js :

import { createDrawerNavigator } from '@react-navigation/drawer'

const Drawer = createDrawerNavigator()

const GymDrawerNavigator = () => {
  return (
    <Drawer.Navigator>
      <Drawer.Screen
        name="Gym"
        component={GymStackNavigator}
      />
    </Drawer.Navigator>
  )
}

GymStackNavigator.js :

import { createStackNavigator } from '@react-navigation/stack'

const Stack = createStackNavigator()

const GymStackNavigator = () => {
  return (
    <Stack.Navigator initialRouteName="GymIndex">
      <Stack.Screen
        name="GymIndex"
        component={GymIndexScreen}
        }}
      />
      <Stack.Screen
        name="GymExerciseIndex"
        component={GymExerciseIndexScreen}
        }}
      />
      ... list of screens
1 Answers

If I understood your problem correctly you want to open the drawer automatically when you navigate to the screen? Add this to the screen components you wish to open the drawer when navigated to.

import {useEffect} from 'react'

...

useEffect(()=>{
  navigation.addListener('focus', () => {
     // when screen is focused (navigated to)
     navigation.openDrawer();
  });  
},[navigation])``
Related