Home > OS >  Get current route name in App.js (no access to navigation prop)
Get current route name in App.js (no access to navigation prop)

Time:05-05

in my react native main file (App.js) I have a handler for firebase notifications, in the foregroundNotifications listener I want to check current route name but problem is I don't have access to navigation prop, that's why I created a ref to navigation in another file which I then import in App.js.

In my RootNavigation.js

import * as React from 'react';

export const isReadyRef = React.createRef();

export const navigationRef = React.createRef();

export function navigate(name, params) {
  if (isReadyRef.current && navigationRef.current) {
    // Perform navigation if the app has mounted
    navigationRef.current.navigate(name, params);
  } else {
    // You can decide what to do if the app hasn't mounted
    // You can ignore this, or add these actions to a queue you can call later
  }
}

This allowed me to use navigate (added the method following another stackoverflow post) , but how can I get current route name from NavigationRoot.js?

How I use it in my App.js (I added navigate, but how can I add getCurrentRoute?)

import { navigationRef, isReadyRef } from '@env/RootNavigation.js';

RootNavigation.navigate('NewScreen');

<NavigationContainer ref={navigationRef} onReady={ () => { isReadyRef.current = true; } }>
            <ROOTSTACK1></ROOTSTACK1>
</NavigationContainer>

CodePudding user response:

Your RootNavigation file should be like in this Example.

add this below function in RootNavigation file

function getCurrentRoute(){
  if (navigationRef.isReady()) {
    const route=navigationRef.getCurrentRoute();
    console.log(route);
   // sample output {key:"Home-k2PN5aWMZSKq-6TnLUQNE",name:"Home"}

   return route.name;
  }
}

And wherever you want to use this function

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

// ...

RootNavigation.getCurrentRoute();

  • Related