How to deep-link from notification in react native app

How to deep-link from notification in react native app

Deep linking is when a link sends users directly into a specific point in the app experience, rather than an external website or app homepage.


Originally posted at ankitkumar.dev


If you have missed an article on How to implement deep linking in React Native app with React Navigation v5, go through it first.

What are we building today?

In the last article, we learned about how to implement deep-links in the react native app with react-navigation v5.

In this article, we will look at how to deep-link content in the app from the notification.

We will use the below deep links and see how the app behaves when this deep link is received in the notification and the user tap on the notification.

  • demo://app/home/:id - This deep link will open the home screen of the app and will pass id as param/props to the home screen
  • demo://app/profile/:id - This deep link will open the profile screen of the app and will pass id as param/props to the profile screen
  • demo://app/notifications - This deep link will open the notifications screen of the app
  • demo://app/settings - This deep link will open the settings screen of the app

After the implementation of the deep link with notification, the app will behave as shown here.

Let’s do some code now!

Setting up the project

I am assuming that you already have a project in which deep links need to be integrated.

If you don’t have any project, I have created a small app with four screens and explained it here.

Setting up the notification in the project

Project is already created in the previous article

I have set up four kinds of local notification in the app

  • Schedule local notification without the deep link

    const scheduleLocalNotification = () => {
      PushNotificationIOS.scheduleLocalNotification({
        alertBody: "Scheduled Local Notification",
        fireDate: new Date(new Date().valueOf() + 2000).toISOString(),
      });
    };
    
  • Local notification that deep-link to profile

const sendProfilNotification = () => {
  PushNotificationIOS.presentLocalNotification({
    alertTitle: "Deep link to profile",
    alertBody: "demo://app/profile/234",
    applicationIconBadgeNumber: 1,
  });
};
  • Local notification that deep-link to settings screen

    const sendSettingsNotificationWithSound = () => {
      PushNotificationIOS.addNotificationRequest({
        id: "notificationWithSound",
        title: "Notification Deep link",
        subtitle: "Received Deep link",
        body: "demo://app/settings",
        sound: "customSound.wav",
        badge: 1,
      });
    };
    
  • Local Notification Request that deep-link to the notifications screen

    const addNotificationRequest = () => {
      PushNotificationIOS.addNotificationRequest({
        id: "test",
        title: "deep link",
        subtitle: "Open notifications",
        body: "demo://app/notifications",
        category: "test",
        threadId: "thread-id",
        fireDate: new Date(new Date().valueOf() + 2000),
        repeats: true,
      });
    };
    

Lets now write functions to handle registering to and unregistering from notification

We will just console log device token on successful registration

  const onRegistered = (deviceToken) => {
    console.log("Registered For Remote Push", `Device Token: ${deviceToken}`);
  };

and console log error message on registration error, if any


  const onRegistrationError = (error) => {
    console.log(`Error (${error.code}): ${error.message}`);
  };

Adding/Removing event listeners on useEffect Hook

Add below code to your app for adding and removing event listeners

  useEffect(() => {
    PushNotificationIOS.addEventListener("register", onRegistered);
    PushNotificationIOS.addEventListener(
      "registrationError",
      onRegistrationError
    );

    PushNotificationIOS.requestPermissions().then(
      (data) => {
        console.log("PushNotificationIOS.requestPermissions", data);
      },
      (data) => {
        console.log("PushNotificationIOS.requestPermissions failed", data);
      }
    );

    return () => {
      PushNotificationIOS.removeEventListener("register");
      PushNotificationIOS.removeEventListener("registrationError");
      PushNotificationIOS.removeEventListener("notification");
      PushNotificationIOS.removeEventListener("localNotification");
    };
  }, []);

Handling onClick of notifcation

Lets now create a function to handle onclick event of notification

  const onLocalNotification = (notification) => {
    const isClicked = notification.getData().userInteraction === 1;
    // Handle deeplink here from notification - done below
  };

We need to add onLocalNotification() to event listeners, so the updated event lister will look like below.

useEffect(() => {
    PushNotificationIOS.addEventListener("register", onRegistered);
    PushNotificationIOS.addEventListener(
      "registrationError",
      onRegistrationError
    );
    PushNotificationIOS.addEventListener(
      "localNotification",
      onLocalNotification
    ); // Handling click on notification

    PushNotificationIOS.requestPermissions().then(
      (data) => {
        console.log("PushNotificationIOS.requestPermissions", data);
      },
      (data) => {
        console.log("PushNotificationIOS.requestPermissions failed", data);
      }
    );

    return () => {
      PushNotificationIOS.removeEventListener("register");
      PushNotificationIOS.removeEventListener("registrationError");
      PushNotificationIOS.removeEventListener("notification");
      PushNotificationIOS.removeEventListener("localNotification");
    };
  }, []);

Let's do magic now

Import Linking from react-native on top of the file.

Modify onLocalNotification() method as below

const onLocalNotification = (notification) => {
    const isClicked = notification.getData().userInteraction === 1;
    Linking.openURL(notification.getMessage());
  };

We are done with the coding part

It was easy, wasn't it?


Video of testing


Full source code can be found on Github Repo

This content is also available as video on YouTube


Further Reading


Also, to be notified about my new articles and stories:

Subscribe to my YouTube Channel

Follow me on Medium, Github, and Twitter.

You can find me on LinkedIn as well.

I am quite active on Dev Community as well and write small topics over there.

Cheers!!! Happy coding!!