How to use withNavigation in react-navigation v5?
Asked Answered
K

2

5

I have a nested component, and I want to use withNavigation in the nested component in react-navigation v5.

Kelikeligot answered 25/5, 2020 at 5:33 Comment(0)
K
8

why you don't create your own withNavigation

import React from 'react';
import { useNavigation } from '@react-navigation/native'; // not sure package name

export const withNavigation = (Component: any) => {
  return (props: any) => {
    const navigation = useNavigation();

    return <Component navigation={navigation} {...props} />;
  };
};
Kenweigh answered 9/9, 2020 at 20:6 Comment(1)
This won't work only If the custom class component is wrapped inside <NavigationContainer>...</NavigationContainer> .Gnu
A
4

React Navigation Version: 5.x Sometimes you need to trigger a navigation action from places where you do not have access to the navigation prop, such as a Redux middleware. For such cases, you can dispatch navigation actions from the navigation container.

If you're looking for a way to navigate from inside a component without needing to pass the navigation prop down. Do not use this method when you have access to a navigation prop or useNavigation since it will behave differently, and many helper methods specific to screens won't be available.

You can get access to the root navigation object through a ref and pass it to the RootNavigation which we will later use to navigate.

// App.js

import { NavigationContainer } from '@react-navigation/native';
import { navigationRef } from './RootNavigation';

export default function App() {
  return (
    <NavigationContainer ref={navigationRef}>{/* ... */}</NavigationContainer>
  );
}

In the next step, we define RootNavigation, which is a simple module with functions that dispatch user-defined navigation actions.

// RootNavigation.js

import * as React from 'react';

export const navigationRef = React.createRef();

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

// add other navigation functions that you need and export them Then, in any of your javascript modules, just import the RootNavigation and call functions that you exported from it. You may use this approach outside of your React components and, in fact, it works just as well when used from within them.

// any js module

import * as RootNavigation from './path/to/RootNavigation.js';

// ...

RootNavigation.navigate('ChatScreen', { userName: 'Lucy' });

Apart from navigate, you can add other navigation actions:

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

export function push(...args) {
  navigationRef.current?.dispatch(StackActions.push(...args));
}

https://reactnavigation.org/docs/navigating-without-navigation-prop/

Anhydrite answered 20/3, 2021 at 8:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.