Search code examples
react-nativereact-navigationreact-navigation-v5

Can I extract all the route keys of react-navigation?


I'm trying to make a key map for all the screens. For that, I need to extract all the keys from navigation container of react-navigation.

For example,

const result = {
   MainScreen: 'Main-p-u9s_rA3z5HCT-KHyDua',
   IndexScreen: 'Index-97mYyg2-P5Kb_wGY4E1ke',
   <RouteName>: <RouteKey>
   ...
}

Is there any solution for this?


Solution

  • You could use getRootState.

    The getRootState method returns a navigation state object containing the navigation states for all navigators in the navigation tree

    export const navigationRef = React.createRef();
    
    const App = () => {
      useEffect(() => {
        const navigationState = navigationRef.current?.getRootState();
    
        const result = {};
        navigationState.routes.forEach(route => {
          result[route.name] = route.key;
        });
        console.log(result);
      }, [navigationRef]);
      return (
        <NavigationContainer ref={navigationRef}>
          <Tab.Navigator>
            <Tab.Screen name="Screen1" component={Screen1} />
            <Tab.Screen name="Screen2" component={Screen2} />
            <Tab.Screen name="Screen3" component={Screen3} />
          </Tab.Navigator>
        </NavigationContainer>
      );
    };
    

    console.log(result) in the code above returns something like this:

    {"Screen1": "Screen1-AVVWEcCJjDeVeO3fu4tgb", "Screen2": "Screen2-nXoQ6xsdjKxoB4hbeXNou", "Screen3": "Screen3-FuFi77tfvex2QXZfin86s"}

    Keep in mind when using getRootState:

    ...the returned state object will be undefined if there are no navigators currently rendered.

    Also look at the navigation state reference.