A Comprehensive Guide to Setting Up React Native Branch for Deep Linking

Deep linking is a feature in mobile apps that lets users navigate directly to specific content within the app through external links. It makes navigation easier and boosts user engagement by quickly taking users to the right place in the app.

In this blog, we’ll learn how to set up deep linking in the React Native Branch using Branch.io, a popular tool for managing and tracking deep links.

What is Branch.io?

Branch.io is a deep linking platform that offers a comprehensive suite of tools to create, manage, and track deep links. It supports both deferred deep linking (when the app is not installed) and contextual deep linking (when the app is installed).

Key Features of Branch.io

  1. Works Everywhere
    Branch.io links work smoothly across Android, iOS, and the web, ensuring a consistent experience on all platforms.
  2. Deferred Deep Linking
    Even if the user doesn’t have the app installed, they can be redirected to the correct content after installing the app.
  3. Detailed Analytics
    Get insights into how your links are performing with metrics like clicks, installs, and user behavior.
  4. Personalized Links
    Create links that are customized for individual users, showing content tailored just for them.

Create a Branch Account

➡️ Go to the Branch.io website: 

      Open the Branch.io Dashboard login in your browser.

➡️ Sign Up for an account:

       Click on the “Sign Up” button and fill in your details like name, email, password, and other information.

➡️ Verify your email:

       Look for a verification email from the Branch in your inbox. Click the link within the email to verify and activate your account.

Log in to the Branch Dashboard

  1. Once your email is verified, log in to Branch.io Dashboard.
  2. You’ll be directed to the Branch Dashboard.

Install Branch.io in a React Native Branch Project

Run the following command to add React Native Branch to your app:

yarn add react-native-branch
cd ios && pod install && cd ..

Create a New App

Navigate to the App section in the left-hand drawer. Here, you will see the default app name displayed. You can edit the app name or add a new app by clicking the appropriate option. A reference screenshot is attached for guidance.

App-Setup

Configure Branch Dashboard

To configure the React Native Branch with your app, navigate to the “Configure” section in the Branch Dashboard. You’ll need details such as:

  • Bundle ID.
  • Package Name.
  • SHA Fingerprint.
  • Apple developer Account Team ID.

Please ensure you have these details ready for a smooth setup process.

🔹Default URL Configuration

In the left menu, under the Configure section, you will find an option called Configuration. Clicking on this option will take you to a page where you can locate the Default URL field. You need to submit your fallback URL here. This URL acts as the fallback for mobile devices that do not have a specified redirect and will open whenever required. A reference screenshot is attached for guidance.

Default-URL-setup

🔹iOS Configuration

iOS-Config-Setup

On the same page, ensure that the “I have an iOS App” & “Enable Universal Links” options are selected. You will be required to provide the following details:

  • iOS URL Scheme (e.g., “myapp://”)
  • Bundle Identifier (e.g., “com.myapp”)
  • Apple App Prefix (Your Team ID from your Apple developer account)

🔹Android Configuration

Android-Config-Setup

On the same page, ensure that the “I have an Android App” and “Enable App Links” options are selected.

You will be required to provide the following details:

  • Android URI Scheme (e.g., “myapp://”)
  • SHA256 Fingerprint of your app’s signing certificate from the keystore (.jks/.keystore) file. The format will look like:

14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5

Build Smarter Apps with Our Mobile App Development Solutions

Set Up Link Domain in Branch Dashboard for Android & iOS

You will also need to specify which link domains your project can expect Branch to use. On the same page, you will find the “Link Domain” section, where you can see the “Default Link Domain” and “Alternate Link Domain” by default. If you have your domain, you can also use that.

Link-Domain-Branch-Setup

🔹iOS Configuration for Link Domain

Go to Xcode and open your project. Then, navigate to the “Signing & Capabilities” tab. You need to add a capability called “Associated Domains”. In this section, add the default and alternate domain links with the applinks: prefix, as shown below. A reference screenshot is also attached for further guidance.

applinks:u604z.test-app.link
applinks:u604z-alternate.test-app.link
applinks:u604z.app.link
applinks:u604z-alternate.app.link

iOS-Xcode-Link-Domain

The branch requires specific key/value pairs to be added to your project’s Info.plist file in two locations:

  1. The Info.plist is located next to the “Signing & Capabilities” tab.
  2. The Info.plist found in your project directory on the left side.

Required Keys:

  • branch_universal_link_domains: Lists your associated domains.
  • branch_key: Contains your Branch live key and optionally your test key.
  • URL types: Defines values for your URL Schemes and URL Identifier.

You can get the Branch Key from the Branch Dashboard. For that, go to the left menu under the Configure section, and you will find an option called Account Settings. Clicking on this option will take you to a page where you can locate the Branch Key field. A reference screenshot is also attached for further guidance.

iOS-Xcode-Link

Branch-Get-Keys

In the AppDelegate.mm file you need to add the following code.

#import <RNBranch/RNBranch.h>
//other imports..

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

//other code...

[RNBranch useTestInstance]; // You need to remove this for production env.
[RNBranch initSessionWithLaunchOptions:launchOptions isReferrable:YES];

//other code...

return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

🔹Android Configuration for Link Domain

To install the Branch.io in Android you need to add dependency in the app level build.gradle file like given below:

dependencies {
   // The version of react-native is set by the React Native Gradle Plugin
   implementation("com.facebook.react:react-android")

   // Required for all Android apps:
   implementation 'io.branch.sdk.android:library:5.12.1' // Check for latest version before hard-coding

   implementation 'store.galaxy.samsung.installreferrer:samsung_galaxystore_install_referrer:4.0.0'
   implementation "com.android.installreferrer:installreferrer:2.2"
   // Required if your app is in the Google Play Store (tip: avoid using bundled play services libs):
   implementation 'com.google.android.gms:play-services-ads-identifier:18.1.0'
}

To set up your app with the Branch Android SDK, update your AndroidManifest.xml file with the required details.

Make sure to collect the following information:

  • App package name.
  • Android URI scheme.
  • App.link domain linked to your app.
  • Alternate app.link domain associated with your app.
  • Branch Live and Test Keys.

You can find the Branch Keys in the Dashboard, as described in the previous steps. Use the sample code for your AndroidManifest.xml below to set up the configuration, and replace all values with your own:

<manifest xmlns:tools="http://schemas.android.com/tools"
   xmlns:android="http://schemas.android.com/apk/res/android">

   <application
     android:name=".MainApplication"
     android:label="@string/app_name"
     android:icon="@mipmap/ic_launcher"
     android:roundIcon="@mipmap/ic_launcher_round"
     android:allowBackup="false"
     android:theme="@style/AppTheme">
       <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
       <meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>
       <activity
         android:name=".MainActivity"
         android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
         android:launchMode="singleTask"
         android:windowSoftInputMode="adjustResize"
         android:exported="true">
         <intent-filter>
             <action android:name="android.intent.action.MAIN" />
             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>

         <!-- Branch URI Scheme -->
         <intent-filter>
             <!-- If utilizing $deeplink_path please explicitly declare your hosts, or utilize a wildcard(*) -->
             <data android:scheme="myapp://" android:host="open" />
             <action android:name="android.intent.action.VIEW" />
             <category android:name="android.intent.category.DEFAULT" />
             <category android:name="android.intent.category.BROWSABLE" />
         </intent-filter>

         <!-- Branch App Links - Live App -->
         <intent-filter android:autoVerify="true">
             <action android:name="android.intent.action.VIEW" />
             <category android:name="android.intent.category.DEFAULT" />
             <category android:name="android.intent.category.BROWSABLE" />
             <data android:scheme="https" android:host="u604z.app.link" />
             <data android:scheme="https" android:host="u604z-alternate.app.link" />
         </intent-filter>

         <!-- Branch App Links - Test App -->
         <intent-filter android:autoVerify="true">
             <action android:name="android.intent.action.VIEW" />
             <category android:name="android.intent.category.DEFAULT" />
             <category android:name="android.intent.category.BROWSABLE" />
             <data android:scheme="https" android:host="u604z.test-app.link" />
             <!-- example-alternate domain is required for App Links when the Journeys/Web SDK and Deepviews are used inside your website. -->
             <data android:scheme="https" android:host="u604z-alternate.test-app.link" />
         </intent-filter>
     </activity>
       <!-- Branch init -->
       <!-- REPLACE `BranchKey` with the value from your Branch Dashboard -->
       <meta-data android:name="io.branch.sdk.BranchKey" android:value="key_live_gqcJRt4sUukrgBUMb4cwBbncsujzZcX7" />
       <!-- REPLACE `BranchKey.test` with the value from your Branch Dashboard -->
       <meta-data android:name="io.branch.sdk.BranchKey.test" android:value="key_test_byeQIw1rHAfviBMTo6lByafnsDnt0wak" />
       <!-- Set to `true` to use `BranchKey.test` -->
     <!-- <meta-data android:name="io.branch.sdk.TestMode" android:value="false" />-->
  </application>
  <queries>
      <intent>
          <action android:name="android.intent.action.SEND" />
          <data android:mimeType="text/plain" />
      </intent>
  </queries>
</manifest>

To initialize the Branch.io in android you need to add code snippet to MainActivity.kt file like give below:

import io.branch.rnbranch.*

override fun onCreate(savedInstanceState: Bundle?) {
 /* RNBootSplash.init(this, R.style.BootTheme) */
 /* SplashScreen.show(this) */
 super.onCreate(savedInstanceState)
 RNBranchModule.initSession(getIntent().getData(), this)
}

override fun onNewIntent(intent: Intent?) {
 super.onNewIntent(intent)
 setIntent(intent)
 RNBranchModule.reInitSession(this)
}

Create Deep Link URLs in the React Native Branch

To generate the deep link URL, you need to follow two steps:

1. Create the Branch Universal Object:

Here, you need to pass the arguments: identifier, which is the unique name for the Branch Universal Object, and options, where you can pass additional parameters.

import branch from 'react-native-branch'

let buo = await branch.createBranchUniversalObject('content/12345', {
  title: 'My Content Title',
  contentDescription: 'My Content Description',
  contentMetadata: {
    customMetadata: {
       key1: 'value1'
    }
  }
})

2. Generate the Short URL, Which is the Sharable Deep Link:

Here, you need to pass linkProperties, which are associated with the URL, and controlParams, which contain parameters for platform fallback URLs. This will return a promise that resolves to a short URL with your specified link properties and parameters.

import branch from 'react-native-branch'

let buo = await branch.createBranchUniversalObject('content/12345', {
  title: 'My Content Title',
  contentDescription: 'My Content Description',
  contentMetadata: {
    customMetadata: {
      key1: 'value1'
    }
  }
})

let linkProperties = {
  feature: 'sharing',
  channel: 'facebook',
  campaign: 'content 123 launch'
}

let controlParams = {
  $desktop_url: 'https://example.com/home',
  custom: 'data'
}

let {url} = await buo.generateShortUrl(linkProperties, controlParams)

Retrieve the Data from the Deep Link URL

To retrieve data from a Branch-generated deep link URL, you need to use the subscribe method of the Branch SDK. This method acts as a listener, fetching and parsing the deep link URL. Using its events, you can access the parameters available in that deep link. You can use the sample code given below:

import React, { useEffect } from 'react';
import branch from 'react-native-branch';

const DeepLinkingListener = () => {
 useEffect(() => {
   const listener = branch.subscribe({
     onOpenStart: ({ uri, cachedInitialEvent }) => {},
     onOpenComplete: async ({ error, params, uri }) => {
       if (error) {
         console.log('subscribe onOpenComplete, Error from opening uri: ' + uri + ' error: ' + error);
         return;
       } else if (params) {
         if (!params['+clicked_branch_link']) {
           if (params['+non_branch_link']) {
             // Route based on non-Branch links
             return;
           }
         } else {
           // Handle params
           // Route based on Branch link data
           return;
         }
       }
     },
   });

   return () => {
    listener();
  };
}, []);

 return null;
};

export default DeepLinkingListener;
coma

Conclusion

In this blog, we explored the process of setting up an account on Branch.io and configuring platform-specific settings. We also demonstrated how to create deep link URLs and extract parameters from them. Integrating deep linking with Branch.io in React Native is easy and brings significant advantages. With features such as deferred deep linking, analytics, and cross-platform compatibility, Branch.io streamlines deep link management. Begin integrating Branch.io today to enhance your app’s user experience and boost engagement.

Start using React Native Branch today to streamline your app’s navigation and boost its functionality.

!! Enjoy, Keep, and Do Delicious Coding !!

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?