React Native OneSignal for Implementing Push Notifications

Learn via video courses
Topics Covered

Overview

react-native-onesignal is a library that allows you to use the native OneSignal SDKs in your React Native app. It exposes a JavaScript API that mirrors the native API, so you can access all the features and functionality of OneSignal from your JavaScript code.

In this article, we will show you how to use react-native-onesignal to implement push notifications in your React Native app.

Prerequisites

Before we start using react-native-onesignal, we need to make sure that we have the following prerequisites:

  1. A React Native project created with either Expo or React Native CLI. If you don’t have one yet, you can follow this guide to create one: React Native Environment Setup
  2. A OneSignal account. If you don’t have one yet, you can sign up for free here: OneSignal Homepage
  3. An Android device or emulator with Google Play Services installed. If you don’t have one yet, you can follow this guide to set up one: Android emulator guidelines
  4. An iOS device or simulator with Push Notifications enabled. If you don’t have one yet, you can follow this guide to set up one: Setting up remote notification server - iOS

Installing React Native OneSignal for Android

To install React Native OneSignal for Android, we need to follow these steps:

  1. Install the react-native-onesignal package using npm or yarn:
  1. Add the following lines to your android/build.gradle file:
  1. Apply the OneSignal Gradle plugin after the Android Gradle plugin by adding this line to your android/app/build.gradle file:
  1. Add your OneSignal App ID to your android/app/build.gradle file:

You can find your OneSignal App ID in your OneSignal dashboard, under Settings > Keys & IDs.

  1. Sync your project and run it on your Android device or emulator.

Installing React Native OneSignal for iOS

To install React Native OneSignal for iOS, we need to follow these steps:

  1. Install the react-native-onesignal package using npm or yarn:
  1. Add your OneSignal App ID to your ios/Podfile file:

You can find your OneSignal App ID in your OneSignal dashboard, under Settings > Keys & IDs.

  1. Add a Notification Service Extension to your Xcode project:
  • In Xcode, go to File > New > Target and select Notification Service Extension.
  • Name it OneSignalNotificationServiceExtension and click Finish.
  • Make sure the Deployment Target is set to iOS 10 or higher.
  • Replace the contents of NotificationService.swift with the following code:
  1. Enable Push Notifications and Background Modes capabilities for both your main app target and your extension target:
  • In Xcode, go to your project settings and select your main app target.
  • Go to Signing & Capabilities and click on + Capability.
  • Search for Push Notifications and add itthemmearch for Background Modes and add them. *themheck the Remote notifications option under Background Modes.
  • Repeat the same steps for your extension target.
  1. Generate a Push Notification certificate for your app:
  • In Xcode, go to your project settings and select your main app target.
  • Go to Signing & Capabilities and click on + Capability.
  • Search for Push Notifications and add it. *themnder Push Notifications, click on the + button next to Development SSL Certificate or Production SSL Certificate, depending on your environment.
  • Follow the instructions to create a certificate request and upload it to Apple Developer Portal.
  • Download the generated certificate and double-click on it to add it to your Keychain Access.
  • Export the certificate as a .p12 file and save it somewhere on your computer.
  1. Upload your Push Notification certificate to OneSignal:
  • In your OneSignal dashboard, go to Settings > Platforms and click on Apple iOS.
  • Under Step 2: Upload Your iOS Push Certificate, click on Choose File and select the .p12 file you exported in the previous step.
  • Enter the password you used to export the file and click Save.
  1. Run your project on your iOS device or simulator.

OneSignal SDK Configuration

Now that we have installed react-native-onesignal for both Android and iOS, we need to configure some settings in our OneSignal dashboard and inanandande.

OneSignal Dashboard Settings

In our OneSignal dashboard, we need to configure some settings for our app, such as:

  • App name and icon
  • Platform and environment
  • Notification permissions and prompts
  • Notification categories and action buttons
  • Segments and filters
  • Delivery and display options
  • Outcomes and attribution

To do this, we need to follow these steps:

  1. Go to our OneSignal dashboard and select our app.
  2. Go to Settings > App Settings and enter our app name and icon.
  3. Go to Settings > Platforms and select the platforms we want to support (Android and iOS in our case).
  4. For each platform, enter the required information, such as:
  • App ID and Google Project Number for Android
  • Bundle ID and Push Certificate for iOS
  • Environment (Development or Production)
  • SDK Version (3.0.0 or higher)
  1. Go to Messages > Templates and create a template for our notifications. We can customize the content, appearance, and behavior of our notifications, such as:

    • Title and message
    • Sound and vibration
    • Badge and priority
    • Category and action buttons
    • Image and video
    • URL and deep link
    • Launch activity or intent
  2. Go to Messages > New Push and create a test push message using our template. We can target our message to specific users or segments, such as:

    • All users or subscribed users
    • Test users or beta users
    • Users with specific tags or external IDs
    • Users in specific locations or languages
    • Users with specific devices or OS versions
  3. Go to Messages > Outcomes and create outcomes for our notifications. Outcomes are events that we want to track when users interact with our notifications, such as:

    • Clicks or opens
    • Purchases or conversions
    • Custom events or goals
  4. Go to Delivery > Delivery Options and configure the delivery options for our notifications, such as:

    • Send now or schedule for later
    • Send once or repeat periodically
    • Send immediately or intelligently
    • Limit frequency or duration
  5. Go to Delivery > Display Options and configure the display options for our notifications, such as:

    • Show heads-up or silent notifications
    • Group notifications by category or app
    • Collapse notifications by key or ID
  6. Save our settings and test our notifications on our devices.

JavaScript OneSignal SDK Initialization

After configuring our OneSignal dashboard settings, we need to initialize the JavaScript OneSignal SDK in our app code. To do this, we need to follow these steps:

  1. Import the OneSignal module in our app entry point file (usually App.js):
  1. Initialize the OneSignal SDK using useEffect() in our root component:

The init method takes two parameters: the OneSignal App ID and an optional settings object. The settings object can have the following keys:

KeyTypeDescriptionDefault
kOSSettingsKeyAutoPromptbooleanWhether to prompt the user for notification permissions automatically or manually.true
kOSSettingsKeyInAppLaunchURLbooleanWhether to launch URLs from notifications in the app or in Brobroowser.true
kOSSettingsKeyInFocusDisplayOptionnumberHow to display notifications when the app is in focus: 0 - None, 1 - InAppAlert, 2 - Notification.0
  1. Add event listeners for notification callbacks using useEffect() in our root component:

The addEventListener() method takes two parameters: the event name and the callback function. The event name can be one of the following:

Event NameDescription
openedFired when a notification is opened by the user.
receivedFired when a notification is received by the device.
idsFired when the device is registered with OneSignal.

The callback function receives an argument that contains the event data. The event data can have the following properties:

PropertyTypeDescription
notificationobjectThe notification object that contains the notification data.
actionobjectThe action object that contains the action data.
deviceobjectThe device object that contains the device data.

The notification object can have the following properties:

PropertyTypeDescription
payloadobjectThe payload object that contains the notification payload data.
isAppInFocusbooleanWhether the app was in focus when the notification was received.
shownbooleanWhether the notification was shown to the user.
silentNotificationbooleanWhether the notification was a silent notification.
displayTypenumberHow the notification was displayed: 0 - None, 1 - InAppAlert, 2 - Notification.

The payload object can have the following properties:

PropertyTypeDescription
notificationIDstringThe unique ID of the notification.
titlestringThe title of the notification.
bodystringThe body of the notification.
soundstringThe sound of the notification.
launchURLstringThe launch URL of the notification.
rawPayloadobjectThe raw payload of the notification.

The action object can have the following properties:

PropertyTypeDescription
typenumberThe type of the action: 0 - Opened, 1 - ActionTaken.
actionIDstringThe ID of the action button that was clicked.

The device object can have the following properties:

PropertyTypeDescription
userIdstringThe OneSignal user ID of the device.
pushTokenstringThe push token of the device.
  1. Remove event listeners for notification callbacks using useEffect() in our root component:

The removeEventListener() method takes two parameters: the event name and the callback function. They should match the ones used in the addEventListener() method.

  1. Define the event handler functions for notification callbacks in our root component:

The event handler functions can access the event data from the argument and perform any logic or UI updates as needed.

Implementation Using a Test Push Message

Let's have a look at the combined code and add notifications permission to it.

Now, we can test our push notifications using a test push message. To do this, we need to follow these steps:

  1. Run our app on our Android device or emulator and/or iOS device or simulator.
  2. Go to our OneSignal dashboard and select our app.
  3. Go to Messages > New Push and create a test push message using our template.
  4. Under Audience, select Test Users and enter our OneSignal user ID or device token. We can find them in our console logs or in our OneSignal dashboard under Audience > All Users.
  5. Click on Send Message and wait for our notification to arrive on our device.
  6. Interact with our notification and observe the behavior and callbacks in our app.

FAQs

Here are some frequently asked questions about React Native OneSignal:

Q How can I prompt the user for notification permissions manually?

A You can use the requestPermissions method to prompt the user for notification permissions manually. For example:

Q How can I check the notification permission status of the user?

A You can use the getPermissionSubscriptionState method to check the notification permission status of the user. For example:

Q How can I subscribe or unsubscribe the user from receiving notifications?

A You can use the setSubscription method to subscribe or unsubscribe the user from receiving notifications. For example:

Q How can I set tags or external user IDs for the user?

A You can use the sendTag, sendTags, deleteTag, deleteTags, or setExternalUserId methods to set tags or external user IDs for the user. For example

Q How can I track events or outcomes when users interact with notifications?

A You can use the sendOutcome, sendUniqueOutcome, or sendOutcomeWithValue methods to track events or outcomes when users interact with notifications. For example:

Conclusion

  • The react-native-onesignal library enables seamless use of native OneSignal SDKs in React Native apps.
  • Installation steps for both Android and iOS platforms are provided, along with prerequisites.
  • Configuring OneSignal dashboard settings allows customization of notification behavior and appearance.
  • Initializing the OneSignal SDK and handling notification events can be achieved through event listeners and callback functions.

To conclude, we've learned how to efficiently implement push notifications in a React Native app using the react-native-onesignal library, providing us with the knowledge and steps needed to incorporate this important feature into our applications.