react-nativestack-navigatorreact-navigation-drawer

How to set action on drawer menu icon while drawer is nested in stack navigation in react native?


I'd created a stack navigation & drawer navigation. The drawer navigation is nested in stack navigation because at first when user opens app for first time then they will see the walkthrough pages and then comes home page which is contains drawer navigation.

Here is the issue, I added image in headerLeft in screenOptions in Drawer.Navigator and on click on it called navigation.openDrawer() but appears that navigation.openDrawer is not a function.

All I want is that, I want to add images in header like as menu for open drawer & other 2 images for goes to other pages and the app logo in center.

below is the code & expo link for full view example:

**APP.JS**
if(isFirstTimeLoad) return (
  <>
    <StatusBar  />
    <Walkthrough onDone={handleDone} />
  </>
);

if(!isFirstTimeLoad) return (
  <NavigationContainer>
    <MainNavigator />
  </NavigationContainer>
)

**MAINNAVIGATOR.JS**
<Stack.Navigator>
  <Stack.Screen name="Home" component={DrawerNavigator} />
</Stack.Navigator>

**DRAWERNAVIGATOR.JS**
<Drawer.Navigator
  useLegacyImplementation
  screenOptions={{
    headerLeft: () => (
      <TouchableOpacity onPress={openDrawer}>
        <Image
          source={require('../assets/menu.png')}
          style={{ height: 20, width: 20 }}
        />
      </TouchableOpacity>
    ),
  }}>
  <Drawer.Screen name="Feed" component={Feed} options={{}} />
  <Drawer.Screen name="Article" component={Article} />
</Drawer.Navigator>

here is the full source code for convinience, expo link : click here


Solution

  • import { useNavigation,DrawerActions } from '@react-navigation/native';
    
    export default function DrawerNavigator(props) {
      // const {navigation} = props
      const navigation = useNavigation();
      const openDrawer = () => navigation.dispatch(DrawerActions.openDrawer());
    
      return (
        <Drawer.Navigator
          useLegacyImplementation
          screenOptions={{
            headerLeft: () => (
              <TouchableOpacity onPress={openDrawer}>
                <Image
                  source={require('../assets/menu.png')}
                  style={{ height: 20, width: 20 }}
                />
              </TouchableOpacity>
            ),
          }}>
          <Drawer.Screen name="Feed" component={Feed} options={{}} />
          <Drawer.Screen name="Article" component={Article} />
        </Drawer.Navigator>
      );
    }
    

    https://snack.expo.dev/hyt2VDjqB

    Try this please :) this works

    Hope it helps,feel free for doubts