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

React Navigation v5: How to use with Branch.io


We have an app utilizing Branch.io universal links. Following the documentation on: https://help.branch.io/developers-hub/docs/react-native#read-deep-link

On the react-native app you setup a subscriber to receive deep and universal links in the javascript runtime.

Using the latest react-navigation from here: https://reactnavigation.org/docs/deep-linking

React Navigation would like to natively handle deep links. React Navigation does not appear to expose a good way to manually launch a link.

How can I utilize these two services together? Taking a deep link and decomposing it into a routable deep link is proving challenging. Our app has nested routers and redoing the translation from path to screens and parameters is something I don't want to do. Has anyone done this recently? Thanks.


Solution

  • You can notify React Navigation about incoming links using the subscribe option:

    const linking = {
      // Custom susbcription to handle incoming links
      subscribe(listener) {
        branch.subscribe(({ error, params, uri }) => {
          if (error) {
            console.error('Error from Branch: ' + error);
            return;
          }
    
          if (params['+non_branch_link']) {
            const nonBranchUrl = params['+non_branch_link'];
            // Route non-Branch URL if appropriate.
            return;
          }
    
          if (!params['+clicked_branch_link']) {
            // Indicates initialization success and some other conditions.
            // No link was opened.
            return;
          }
    
          // A Branch link was opened
          const url = params.$canonical_url;
    
          listener(url);
        });
    
        return () => {
          // Clean up the event listeners
          branch.unsubscribe();
        };
      },
      // Options such as prefixes, screens config etc.
      // ...
    };
    

    Docs: https://reactnavigation.org/docs/deep-linking/#third-party-integrations