reactjsreact-nativereact-navigationreact-navigation-v6

Deeplinking multiple paths for a screen in react-navigation 6+


I have some screens that need to support multiple deep linking paths like this:

export const navigationConfig = {
  prefixes: supportedDeepLinkURLs,
  config: {
    screens: {
      Root: {
        path: '',
        screens: {
          Article: {
             path: [ // This needs to be an array not a string 
                'teams/first-team/content/:id',
                'teams/handball/content/:id',
                'teams/club/content/:id',
            ],
            exact: false
          },
         // ...
        }
     }
    }
  }

Is there any way in react-navigation 6 deeplinking that an array or regex could be provided as a path?

There is an old answer here: react-navigation deep linking with multiple paths

for react-navigation 4 or 5 but I couldn't find anything in react-navigation 6 docs about this.

Any help or suggestion will be greatly appreciated.

Thank you!


Solution

  • The URL Path is expected to be a string, not an array. A brute force solution, you can add different route names related to FirstTeam, HandBall, and Club as below:

    const paths = [
      "teams/first-team/content/:id",
      "teams/handball/content/:id",
      "teams/club/content/:id",
    ];
    
    function getPathName(path) {
      return path.split("/")[1];
    }
    function generatePaths(paths) {
      let screenPaths = {};
    
      paths.forEach((path) => {
        const pathName = getPathName(path);
        screenPaths[pathName] = {
          path,
        };
      });
      
      return screenPaths
    }
    
    export const navigationConfig = {
      prefixes: supportedDeepLinkURLs,
      config: {
        screens: {
          Root: {
            path: '',
            screens: {
              ...generatePaths(paths)
            },
            
         }
        }
      }}
    
    const renderDynamicRoutes = () =>
      paths.map((path) => (
        <Stack.Screen
          key={path}
          name={getPathname(path)}
          component={ArticleScreen}
        />
      ))
    
    
    <Stack.Navigator>
    {renderDynamicRoutes}
      {/* other stack navigator routes*/}
    </Stack.Navigator>