While using react-navigation in pair with react-native or a classic web based react app, you probably someday asked yourself:

« How could I get the current route metadata such as route name ? »

This is a pretty common use case, but sometimes it might get a little bit tricky and it can be difficult to find out how to deal with that.

This is the reason I’m sharing with you this small guide to overcome most failure cases you might experiencing, after several hours of struggling, I hope this pattern will helps you not ending in the same situation I was.

👨🏻‍🔬 Let’s start with a little bit of theory

In our application context, within react-navigation logic, we will encounter two kind of components:

Direct child of a navigator components, which are called screen components. Any others nested children of the navigation tree, which are not screens components, I will call screen component’s nested children.

And there is the main pitfall, depending on the component context, the navigation state you are getting from props is not the same

Let’s see together what we can do to get current screen metadata properly.

➡️ Getting current screen metadata from screen components

A screen component is a direct child of a navigator.

MainScreen and SelectPlayersScreen are direct children of your SwitchNavigator.

This is pretty simple here: as long your screen is a direct child of your navigator, you just have to rely on props.navigate.state or const navState = useNavigationState() from react-navigation-hooks .

This will give you the metadata you need for your screen such has the routeName .

➡️ Getting current screen metadata from screen component’s nested children

If the component where you need the value is not a direct navigation child, whether by using the withNavigation HOC, the useNavigation or useNavigationState hooks, therefore you will probably get the entire state tree as react-navigation will not able to resolve the current context.

✋🏻⚠️ Caution: You could pass down the value from the screen component to the children using props, this is the preferred approach you should consider to use. But if you can’t and you are deep nested in the component tree, you can use the following snippet plus some traditional code, that will help you deal with that issue.

getActiveRouteMetadata is a small utility function that will helps you retrieve your current screen metadata from the complete navigation state tree object.

A small utility function to dig into the navigation state tree

Just pass the navigation state like so and you’re fine!

import { useNavigationState } from "react-navigation-hooks"; function MyNestedComponent(){

const navState = useNavigationState();

const myScreenMetadata = getActiveRouteMetadata(navState); return (

// … your component JSX …

)

}

🚛 Takeaway / TLDR; 📦

In react-navigation: to get metadata of the current active route there is two way that will depends on the context you actually are: