Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use useNavigation() within @react-navigation drawer?

Current Behavior

I have a react-native application that use react-navigation v5 for the routing.

  1. I have a drawer (offeset menu left) in all my views
  2. I use the stackNavigation for page transition.

Because of (1), my structure is drawerNavigator (a) > stackNavigator (b) > views (c).

When I try to call the useNavigation() hook within my <DrawerContent />, I have the following error:

Error: We couldn't find a navigation object. Is your component inside a navigator?
    at useNavigation (bundle.js:8766)

Yes, I am not inside the stackNavigator so the hook cannot be called

Expected Behavior

I expect to have navigation available within my <DrawerContent />.

Your Environment

| software                       | version |
| ------------------------------ | ------- |
| iOS or Android                 | iOS, Android and web
| @react-navigation/native       | 5.0.0-alpha.41
| @react-navigation/stack         | 5.0.0-alpha.63
| @react-navigation/drawer       | 5.0.0-alpha.41
| react-native-reanimated        | 1.4.0
| react-native-gesture-handler   | 1.5.3
| react-native-safe-area-context | 0.6.2
| react-native-screens           | 2.0.0-alpha.32
| react-native                   | https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz
| expo                           | SDK36
| node                           | v13.5.0
| npm or yarn                    | 6.13.7

How can I use @react-navigation/stack inside @react-navigation/drawer or how should I build my drawer and app with them?

like image 319
Dimitri Kopriwa Avatar asked Feb 06 '20 04:02

Dimitri Kopriwa


People also ask

How do you use useNavigation in react?

Step 1: To start with, create a React application using the following command: npx create-react-app <project_name>; Step 2: Install the latest version of react-router-dom in the React application by the following. Project Structure: Create a folder named components in the src folder and add files Home.


1 Answers

This is possible using https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html

Create RootNavigation :

import { createRef } from 'react';

export const navigationRef = createRef();

export function navigate(name, params) {
  navigationRef.current?.navigate(name, params);
}

export function goBack() {
  navigationRef.current?.goBack();
}

In App.js:

import { navigationRef } from './navigation/RootNavigation';
// ...
<NavigationContainer
  ref={navigationRef}
>
  {children}
</NavigationContainer>

Then import RootNavigation from any source and you will not have to worry about the react tree.

like image 123
Dimitri Kopriwa Avatar answered Sep 19 '22 19:09

Dimitri Kopriwa