React Native - Accessing drawer navigation outside of AppNavigator

3.7k Views Asked by At
  App.js 
    <Store>
      <Navbar />
      <AppNavigator ref={navigatorRef => {
          NavigationService.setTopLevelNavigator(navigatorRef);
        }} />
    </Store> 

I wanna be able to access

 props.navigation.openDrawer();

from navbar but I get

undefined is not an object (evaluating 'props.navigation.openDrawer')

onPress
    Navbar.js:70:29
    etc..

How can I allow NavBar to access the drawer?

2

There are 2 best solutions below

2
On BEST ANSWER

I suppose you are following Navigating without the navigation prop (if you don't then you should in your case). Then in NavigationService.js add openDrawer method

// NavigationService.js

import { DrawerActions } from 'react-navigation-drawer';

...

// add this function
function openDrawer(routeName, params) {
  _navigator.dispatch(DrawerActions.openDrawer());
}


export default {
  ...
  // and export it
  openDrawer
};

then instead of props.navigation.openDrawer(), use

NavigationService.openDrawer()

don't forget to make respective imports

0
On

this is how i used openDrawer without navigation prop:

in your App.js (or other router)

1/

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

2/

export const navigationRef = React.createRef();

3/

export function openDrawer(routeName, params) {
  navigationRef.current.dispatch(DrawerActions.openDrawer());
}

4/ inside your navigation container add this ref

<NavigationContainer ref={navigationRef}> 

5/ call your function somewhere where openDrawer is created:

<TouchableOpacity onPress={() => openDrawer()}>
        <Image
          source={tab}
          style={{
            width: 20,
            height: 20,
          }}
        />
</TouchableOpacity>