Deep linking (opening web with mobile app) in React Native and Expo

Tiempo de lectura: 2 minutos

Reading time: 2 minutes

Hello, today I’m going to show you how to use Deep Links with React Native.

The first thing we’re going to do is install the Deep Linking library from Expo (https://reactnavigation.org/docs/deep-linking/)

npx expo install expo-linking

Once installed, go to app.json and add our web schema (which we’ll accept as a link)

{
  "expo": {
    "scheme": "myapp"
  }
}

In this case, the specified schema corresponds to the first part of the link myapp://, meaning it will open all URLs that start with that prefix.

If we want to open universal links with https/http, we’ll need to use Deep Links in Android and Universal Links in iOS. To do this, add the following code inside Android:

{
"expo": {
    "android": {
    "intentFilters": [
        {
        "action": "VIEW",
        "data": [
            {
            "scheme": "https",
            "host": "ourapp.com"
            }
        ],
        "category": ["BROWSABLE", "DEFAULT"]
        }
    ]
    }
}
}

This is equivalent to the code we add in the Android manifest natively (we don’t need to add it now)

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data
                    android:host="ourapp.com"
                    android:scheme="https" />

In the case of iOS, do the following:

"ios":{
"applinks": {
    "apps": [], 
    "details": [
    {
        "appID": "TEAM_ID.com.example.app",
        "paths": ["*"]
    }
    ]
}
}

Replace TEAM_ID with your iOS team ID.

To make applinks work correctly, you’ll need to host an associated domain link on your website: https://developer.apple.com/documentation/xcode/supporting-associated-domains

Now let’s go to our app.js and add the dependencies and code to handle our links:

import * as Linking from 'expo-linking';

Once expo-linking is imported, add the links that we’re going to accept inside our render method.

const linking = { prefixes: [Linking.createURL('/'), 'https://example.com'],};

And add it to a navigation container:

  <NavigationContainer linking={linking}>

Another option is to handle the link that opens the app. For this, add the following code:

In our app.js, add the following inside the render method:

 const url = Linking.useURL();

And inside useEffect, we can print the received value:

    useEffect(() => {
        if (url) {
            alert(url);
        }
    }, [url]);

Leave a Comment