Wednesday, May 3, 2023
HomeRuby On RailsDeep hyperlinks in React Native

Deep hyperlinks in React Native


Not too long ago I had the privilege of consulting with a shopper and their group of cell engineers on a React Native utility. Working with them gave me a substantial amount of new expertise and insights into creating React Native purposes. One of many challenges I had the chance to assist them with was including deep hyperlink and common hyperlink options to their cell app.

In a cell app deep hyperlinks add a approach for the app to acknowledge a hyperlink schema and deal with incoming hyperlinks, routing to the suitable display screen. The schema will look one thing like:

These hyperlinks are sometimes utilized in push notifications in order that messages to a consumer can open to a desired place within the app, prompting the consumer to take motion or presenting them with well timed data. An app developer also can use deep hyperlinks to permit third celebration apps to hyperlink to content material or actions inside their app.

Common hyperlinks are just like deep hyperlinks. They’re HTTPS-based URLs, almost definitely shared with an online area. As soon as common hyperlinks are configured, a URL is ready to open on the net or the app based mostly on whether or not or not the app is put in. A common hyperlink could appear to be:

https://app.instance.com/path/to/display screen

Common hyperlinks are sometimes used to create a fluid expertise for apps that improve or prolong an online expertise. Corporations corresponding to Reddit use common hyperlinks to unify the expertise between their internet content material and their app. When a common hyperlink is opened in a cell internet browser, an app banner shall be proven to let customers know the corporate provides an app for added options. Then if a consumer already has the app put in, the hyperlink will take them on to the content material inside the app.

The work I did for our shopper is proprietary so for the aim of demonstrating deep hyperlink setup I’ve created a fundamental React Native utility, Espresso Notes. Espresso Notes is a quite simple app for taking notes about one’s every day espresso brew. Supply code for Espresso Notes is offered on GitHub so be happy to construct it and check out it out.

Coffee Notes app


One of many many causes to decide on React Native for a cell app is the power to construct each Android and iOS apps from the identical code. React Native conveniently abstracts away lots of the native considerations of iOS and Android. Which means that for many elements of the appliance, builders are in a position to construct screens and elements utilizing JavaScript or TypeScript with out worrying concerning the implementation particulars of every cell platform.

Some considerations, nevertheless, do require involvement within the native code—and including deep hyperlinks is a type of considerations. React Navigation, the beneficial library for navigation in React Native, handles a great deal of deep hyperlink logic. Their documentation provides guides on the native code that can must be added.

iOS Native Configuration

Step one is to inform the iOS app concerning the navigation package deal put in by React Navigation. To try this I’ll observe the documentation’s directions to override the utility:openURL:choices: technique of the iOS AppDelegate. AppDelegate.m is the entry level for iOS purposes and is written in Goal-C.

// Add this header on the high of the file:
#import <React/RCTLinkingManager.h>

// Add the next features inside `@implementation AppDelegate` above `@finish`:
- (BOOL)utility:(UIApplication *)utility
   openURL:(NSURL *)url
   choices:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)choices
{
  return [RCTLinkingManager application:application openURL:url options:options];
}

Android Native Configuration

Persevering with to observe React Navigation’s information, some Android native adjustments must be made too. AndroidManifest.xml is the basis configuration definition for the Android utility. Right here the documentation instructs us so as to add a brand new intent-filterconfiguration part. Within the Android configuration the intent-filter tag defines intents that an utility exercise can reply to. This instance defines an intent that can reply to a deep hyperlink schema beginning with coffeeNotes://.

<exercise>
 ...
  <intent-filter>
      <motion android:identify="android.intent.motion.VIEW" />
      <class android:identify="android.intent.class.DEFAULT" />
      <class android:identify="android.intent.class.BROWSABLE" />
      <knowledge android:scheme="coffeeNotes" />
  </intent-filter>
 ...
</exercise>

Elective: Net Configuration for Common Linking

I received’t be capable of exhibit common hyperlinks with the Espresso Notes instance, as a result of including related domains in Xcode requires an lively Apple Developer account. However this can be a very helpful configuration, so I’ll cowl the online aspect setup. When organising common hyperlinks, your app is ready to reply to an online URL. Apple and Android each require that app-to-web associations be verified, and that verification should be added on the net.

Apple specifies configure this of their documentation on supporting related domains. Right here’s an instance of how I’d arrange the Espresso Notes app.

<website>/.well-known/apple-app-site-association

{
  "applinks": {
      "particulars": [
           {
             "appIDs": [ "App ID here" ],
             "elements": [
               {
                  "/": "/*",
                  "comment": "Matches any URL to this subdomain"
               }
             ]
           }
       ]
   }
}

Android has the same configuration file and describes it of their Verifying Android App Hyperlinks documentation. Here’s what I’d add to an online area related to this app:

<website>/.well-known/assetlinks.json

[
  {
    "relation": ["delegate_permission/common.handle_all_urls"],
    "goal": {
      "namespace": "android_app",
      "package_name": "com.coffeenotes",
      "sha256_cert_fingerprints":
        ["SHA256 fingerprints here"]
    }
  }
]

Configuration for React Navigation

Okay, we’re lastly to the JavaScript half (or TypeScript if that’s your choice).

Reminder: that is the best way to do that when utilizing React Navigation – at present the beneficial library for navigation in React Native purposes in accordance with their documentation.

The React Navigation documentation instructs us to wrap the entire utility in a <NavigationContainer>. This supplies all screens beneath it a context for navigating to different screens.

That is additionally the place we have to add the React Native configuration for deep hyperlink paths. NavigationContainer accepts a prop referred to as linking. Right here I’ll inform React Native concerning the paths I anticipate it to have the ability to deal with. For this Espresso Notes app I’d like to have the ability to deep hyperlink to the Dwelling Display and likewise a particulars display screen I’ll name CoffeeNote.

// Instance
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {NavigationContainer} from '@react-navigation/native';

const Stack = createNativeStackNavigator<RootStackParamList>();

const RootStack = () => {
  return (
    <Stack.Navigator initialRouteName="Dwelling">
      <Stack.Display identify="Dwelling" part={Dwelling} />
      <Stack.Display identify="CoffeeNote" part={CoffeeNote} />
    </Stack.Navigator>
  );
};

export const LinkingConfig = {
  prefixes: ['coffeeNotes://'],
  config: {
    screens: {
      Dwelling: 'house',
      CoffeeNote: 'coffee_note/:id?',
    },
  },
}

operate App() {
  return (
    <NavigationContainer linking={LinkingConfig}>
      <RootStack />
    </NavigationContainer>
  )
}

At this level the Espresso Notes app ought to be capable of deal with two completely different deep hyperlinks paths: /house and /coffee_notes/some_id. Extra advanced paths might be configured, however this can be a nice begin. Try React Navigation’s documentation for all the small print.

Let’s take a look at out what we’ve executed to this point!

Admittedly that was a big quantity of boilerplate. As soon as all that configuration is in place, I’d like to ensure these deep hyperlinks work as supposed. The iOS Simulator and Android Emulator are a fast place to check out a React Native utility.

I’d warn that I’ve witnessed inconsistent conduct between simulators/emulators and bodily units. So I like to recommend verifying your adjustments on a bodily iPhone and/or Android earlier than releasing to app shops.

On simulators/emulators you’ll be able to take a look at your deep hyperlinks from the command line or you might choose to check hyperlinks on an actual machine. I discover the command line instruments handy for repeatability so I’ll exhibit that technique right here. A JavaScript package deal referred to as uri-scheme supplies a helper for working on both iOS or Android.

To simulate opening a deep hyperlink in your platform run:

npx uri-scheme open "coffeeNotes://" --[ios | android]
GIF showing a deep link opening the the app on iOS simulator

It is best to see the app open on account of that command. Since no path was given the app received’t try to navigate anyplace. We are able to attempt once more with coffeeNotes://house; this could navigate again to the Dwelling display screen from anyplace else within the app.

It might be good to know we will hyperlink to precise content material from deep hyperlinks. Up to now I’ve proven a fairly empty model of the app. I’ve now added some knowledge to the app, a couple of espresso notes, in order that we will attempt linking to one in all them.

Screenshot: Coffee Notes ap with some data

The espresso word IDs are fundamental integers beginning at 1. Primarily based on the configuration added earlier the Espresso Notes app ought to be capable of deal with a deep hyperlink to a selected word. To exhibit I’ll run:

npx uri-scheme open coffeeNotes://coffee_note/1 --ios

The app ought to open to the word from November 5.

GIF showing a deep link opening a coffee note screen

That’s it! The Espresso Notes app has a minimal quantity of navigation and linking that I can construct upon because it grows.

RELATED ARTICLES

Most Popular

Recent Comments