React Native OneSignal for Implementing Push Notifications
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:
- 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
- A OneSignal account. If you don’t have one yet, you can sign up for free here: OneSignal Homepage
- 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
- 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:
- Install the react-native-onesignal package using npm or yarn:
- Add the following lines to your android/build.gradle file:
- Apply the OneSignal Gradle plugin after the Android Gradle plugin by adding this line to your android/app/build.gradle file:
- 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.
- 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:
- Install the react-native-onesignal package using npm or yarn:
- 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.
- 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:
- 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.
- 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.
- 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.
- 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:
- Go to our OneSignal dashboard and select our app.
- Go to Settings > App Settings and enter our app name and icon.
- Go to Settings > Platforms and select the platforms we want to support (Android and iOS in our case).
- 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)
-
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
-
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
-
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
-
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
-
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
-
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:
- Import the OneSignal module in our app entry point file (usually App.js):
- 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:
| Key | Type | Description | Default |
|---|---|---|---|
| kOSSettingsKeyAutoPrompt | boolean | Whether to prompt the user for notification permissions automatically or manually. | true |
| kOSSettingsKeyInAppLaunchURL | boolean | Whether to launch URLs from notifications in the app or in Brobroowser. | true |
| kOSSettingsKeyInFocusDisplayOption | number | How to display notifications when the app is in focus: 0 - None, 1 - InAppAlert, 2 - Notification. | 0 |
- 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 Name | Description |
|---|---|
| opened | Fired when a notification is opened by the user. |
| received | Fired when a notification is received by the device. |
| ids | Fired 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:
| Property | Type | Description |
|---|---|---|
| notification | object | The notification object that contains the notification data. |
| action | object | The action object that contains the action data. |
| device | object | The device object that contains the device data. |
The notification object can have the following properties:
| Property | Type | Description |
|---|---|---|
| payload | object | The payload object that contains the notification payload data. |
| isAppInFocus | boolean | Whether the app was in focus when the notification was received. |
| shown | boolean | Whether the notification was shown to the user. |
| silentNotification | boolean | Whether the notification was a silent notification. |
| displayType | number | How the notification was displayed: 0 - None, 1 - InAppAlert, 2 - Notification. |
The payload object can have the following properties:
| Property | Type | Description |
|---|---|---|
| notificationID | string | The unique ID of the notification. |
| title | string | The title of the notification. |
| body | string | The body of the notification. |
| sound | string | The sound of the notification. |
| launchURL | string | The launch URL of the notification. |
| rawPayload | object | The raw payload of the notification. |
The action object can have the following properties:
| Property | Type | Description |
|---|---|---|
| type | number | The type of the action: 0 - Opened, 1 - ActionTaken. |
| actionID | string | The ID of the action button that was clicked. |
The device object can have the following properties:
| Property | Type | Description |
|---|---|---|
| userId | string | The OneSignal user ID of the device. |
| pushToken | string | The push token of the device. |
- 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.
- 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:
- Run our app on our Android device or emulator and/or iOS device or simulator.
- Go to our OneSignal dashboard and select our app.
- Go to Messages > New Push and create a test push message using our template.
- 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.
- Click on Send Message and wait for our notification to arrive on our device.
- 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.