How can I know my current route in react-navigation 5?

15,016

Solution 1

I am using the following approach to get the current route name in react-navigation v5. https://reactnavigation.org/docs/navigation-prop/#dangerouslygetstate

const {index, routes} = this.props.navigation.dangerouslyGetState();
const currentRoute = routes[index].name;
console.log('current screen', currentRoute);

Solution 2

The NavigationContainer has onStateChange prop, useful for this case, check react-navigation docs Screen Tracking for analytics and if you need access without navigation prop see Navigating without the navigation prop

I share the code to get only active routeName

function App(){
    const routeNameRef = React.useRef();
    // Gets the current screen from navigation state
    const getActiveRouteName = (state)=> {
        const route = state.routes[state?.index || 0];

        if (route.state) {
          // Dive into nested navigators
          return getActiveRouteName(route.state);
        }

        return route.name;
    };

    return (<NavigationContainer
    onStateChange={(state) => {
      if (!state) return;
      //@ts-ignore
      routeNameRef.current = getActiveRouteName(state);
    }}
    >
    ...
    </NavigationContainer>)
}

Solution 3

If you want to know the current screen from a component you can also use this:

export const HomeScreen = ({ navigation, route }) => {

    console.log(route.name);

    return (
        {...}
    );
};

Solution 4

It is possible to get this from the navigationRef attached to the navigation container. Where navigationRef is a ref.

export const navigationRef = React.createRef()

and

<NavigationContainer
   ref={navigationRef} 
   >
  <Navigator />
</NavigationContainer>

Then use: const currentRouteName = navigationRef.current.getCurrentRoute().name to get the current route name.

Alternatively in a functional component you can useRef const navigationRef = React.useRef()

Share:
15,016
Dimitri Kopriwa
Author by

Dimitri Kopriwa

Advanced expertise in Internet technologies. Fully familiar with the DevOps movement, we do apply Agile development methodologies proven to create state-of-the-art software solutions, designed to scale globally. As R&amp;D experts in Web technologies, we bring digital innovation added value to your business. If strengthening your information systems and developing your business through continuous improvements is your growth path, then our visions converge. Previously, at Moma Group R &amp; D on the Voltalis energy saving project our aim was to promote responsible and sustainable use of electrical energy. In addition, we have also created technologies for cleaner energy.

Updated on July 09, 2022

Comments

  • Dimitri Kopriwa
    Dimitri Kopriwa almost 2 years

    I am using this https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html to access my navigation from any source, my file look as follow:

    import { createRef } from 'react';
    
    export const navigationRef = createRef();
    
    export function navigate(name, params) {
      return navigationRef.current?.navigate(name, params);
    }
    
    export function goBack() {
      return navigationRef.current?.goBack();
    }
    
    export function getRootState() {
      return navigationRef.current?.getRootState();
    }
    

    This is perfect for my @navigation/drawer, which is outside my stack navigation.

    Only one problem the last method is not synchronized and I want to have an active state on my item menu that is the current route.

    How is that possible with react navigation 5?

    • Hend El-Sahli
      Hend El-Sahli over 4 years
      Try this: navigation.state.routes[navigation.state.index].routeName ... it depends on the structure of your navigation ... so try to console.log navigation.state, and you will get to what you want...
    • Dimitri Kopriwa
      Dimitri Kopriwa over 4 years
      Well, I can't. I am not using v4. In v5, I must use useNavigation() to access the navigation and because I am outside the stack navigator (I am into the DrawerContent of the drawer navigator and it wrap the stack navigator), then I can't access the navigation object this way. This is why I have linked this : reactnavigation.org/docs/en/…
    • Hend El-Sahli
      Hend El-Sahli over 4 years
      if you want to access navigation object inside a contentComponent of the Drawer: You could try this: this.props.descriptors.YourStackIdentifer.navigation ... I mean navigation object is there in the props without the need to inject it using useNavigation or anything like that...
    • Dimitri Kopriwa
      Dimitri Kopriwa over 4 years
      I use <DrawerNavigator drawerContent={DrawerContent}><Stack.Navigator><ScreenList /></Stack.Navigator></DrawerNavigator>, in order to use useNavigation, you MUST be in <Stack.Navigator /> tree, but DrawerContent is not so it is not possible to use useNavigation. Also, navigation is not injected into DrawerContent.
    • Oska Ng
      Oska Ng over 4 years
      I'm have same issues with you, i tried with useNavigation() and useNavigationState() but always have not latest state. Maybe you can try this way, i think currently only this way can achive State Persistance. By using AsyncStorage to get latest state or create a context provider to store the state when change update the context.
    • Sanchitos
      Sanchitos about 4 years
      Please checkout the answer here: stackoverflow.com/questions/59005239/…
  • Chandreu
    Chandreu almost 4 years
    My mistake, that line was not necessary. I've edited it out.
  • kd12345
    kd12345 over 3 years
    hi hope you are good, can you please have a look at my question? stackoverflow.com/questions/66548327/…
  • kd12345
    kd12345 over 3 years
    hi hope you are good, can you please have a look at my question? stackoverflow.com/questions/66548327/…
  • kd12345
    kd12345 over 3 years
    hi hope you are good, can you please have a look at my question? stackoverflow.com/questions/66548327/…
  • Mike Vargas
    Mike Vargas over 3 years
    @kd12345 Sure, I do it