React Native Push
Notifications: Your Ultimate
Guide
Abbas Ali Radiowala
·
Follow
9 min read
336
8
Hi Geeks !! In this fast-paced world of mobile app
development, Push Notifications play a pivotal role in
engaging users and delivering timely updates. In this
post, we’ll learn how to setup Push notification in
React Native apps using react-native-push-
notification module. We’ll be utilizing the Firebase
console to dispatch notifications and capture them
within our app. Additionally, we’ll delve into the
process of managing push notifications in React
Native applications. This includes accessing the data
transmitted via notifications within the app and
ensuring the app wakes up if it’s inactive or closed.
What are Push Notifications
Push notifications are messages or alerts sent by
mobile applications to users’ devices, even when the
app is not actively in use. These notifications can
contain various types of information, such as updates,
reminders, promotions, or personalized messages.
They appear as banners, alerts, or badges on the
device’s home screen, lock screen, or notification
center, depending on the device’s operating system
and user settings.
Setting up a React Native App for receiving Notifications
In this tutorial, our focus will be on setting up push
notification reception within a React Native
application specifically for Android devices. The code
provided will be compatible with both Android and
iOS platforms, but for iOS, additional configuration
steps are required. We’ll cover those steps in a
separate tutorial dedicated to iOS setup.
To create a new React Native app, you can use the
following command in your terminal:
npx react-native init Notification
This command initializes a new React Native project
with the specified name. Make sure you have Node.js
and npm (or Yarn) installed on your system before
running this command.
You can run the Android application with the
following code snippet:
npm run android
Creating the Push Notification Dependency
In this setup, we’re utilizing the ‘react-native-push-
notification’ package, specifically designed to handle
push notification functionality within our React Native
application. You can acquire this package via Node
Package Manager (npm).
npm install --save react-native-push-notification
or
yarn add react-native-push-notification
Registering our Application with Firebase
Within the Firebase dashboard, you need to register
your Android or iOS application to enable push
notifications. For this demonstration, we’ll focus on
implementing push notifications for Android apps.
To register your Android application in the Firebase
dashboard, follow these steps:
1. Register the Android application and give it a
name.
2. Select your project or create a new one if you
haven’t already.
3. Click on the “Add app” button to add a new
platform to your project.
4. Choose the Android platform by clicking on
the Android icon.
5. Enter your Android app’s package name. This
can typically be found in the
“android/app/build.gradle” file of your React
Native project.
6. (Optional) Enter other optional details such as
app nickname and debug signing certificate
SHA-1.
7. Click on the “Register app” button to
complete the registration process.
Tip: To get SHA-1 or SHA-256 certificate go to your
project in cmd and then type the following command.
cd android
./gradlew signingReport
After downloading the google-services.json file from the
Firebase console, ensure you place it in the root
directory of your application module.
Next, incorporate the necessary code provided by
Firebase documentation into the project-level
build.gradle file (located at <project>/build.gradle). This
code snippet configures your project to work with
Firebase services.
buildscript {
ext {
...
buildToolsVersion = "34.0.0"
minSdkVersion = 21
compileSdkVersion = 34
targetSdkVersion = 34
ndkVersion = "25.1.8937393"
kotlinVersion = "1.8.0"
...
repositories {
...
google() // Add this line
mavenCentral()
...
dependencies {
...
classpath("com.google.gms:google-services:4.4.0") // Google
Service Plugin
...
apply plugin: "com.facebook.react.rootproject"
After completing the project-level configuration,
proceed to create the application-level build.gradle file
located at <project>/<app-module>/build.gradle.
...
apply plugin: "com.google.gms.google-services"
...
dependencies {
...
implementation(platform("com.google.firebase:firebase-
bom:32.7.1"))
...
To incorporate Push Notifications into your React
Native Android application, replace the following
code snippet to your AndroidManifest.xml file.
<manifest
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission
android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
// Permission for requesting Notification Access
<uses-permission
android:name="android.permission.POST_NOTIFICATIONS"/>
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="@style/AppTheme">
<meta-data
android:name="com.dieam.reactnativepushnotification.notification_
foreground"
android:value="true" />
<meta-data
android:name="com.dieam.reactnativepushnotification.channel_creat
e_default"
android:value="true" />
<meta-data
android:name="com.dieam.reactnativepushnotification.notification_
color"
android:resource="@color/white" />
<receiver
android:name="com.dieam.reactnativepushnotification.modules.RNPus
hNotificationActions"
android:exported="true" />
<receiver
android:name="com.dieam.reactnativepushnotification.modules.RNPus
hNotificationPublisher"
android:exported="true" />
<receiver
android:name="com.dieam.reactnativepushnotification.modules.RNPus
hNotificationBootEventReceiver"
android:exported="true">
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED" />
<action
android:name="android.intent.action.QUICKBOOT_POWERON" />
<action
android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service
android:name="com.dieam.reactnativepushnotification.modules.RNPus
hNotificationListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"
/>
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|
screenLayout|screenSize|smallestScreenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Lastly, go to
android/app/src/res/values/colors.xml. If the file
does not exist, create it. This file determines the color
of the notification on an Android device.
<resources>
<color name="white">#FFF</color>
</resources>
After configuring all the above steps, follow the below
step to check if there is any dependency issue or error
being raised while adding all the functionalities for
Push Notification.
// Go to Project Folder and follow these steps
// Navigate to android folder
cd android
// Use this command to check for any error or dependency issue
./gradlew clean
As of now, all the dependency has been added and
we’ll now move onto the next set of steps i.e.
receiving notifications.
All the functionalities & logics must always be applied
to the root level of the project, not inside any
component as Notification requires access to the entire
app.
Configuring Local Notification
In your React Native project, open your App.tsx or
create a new file in your root directory. Import the
PushNotification module from react-native-push-
notification, and initialize it.
import PushNotification from 'react-native-push-notification'
const LocalNotification = () => {
const key = Date.now().toString(); // Key must be unique
everytime
PushNotification.createChannel(
channelId: key, // (required)
channelName: "Local messasge", // (required)
channelDescription: "Notification for Local message",
// (optional) default: undefined.
importance: 4, // (optional) default: 4. Int value of
the Android notification importance
vibrate: true, // (optional) default: true. Creates
the default vibration patten if true.
},
(created) => console.log(`createChannel returned '$
{created}'`) // (optional) callback returns whether the channel
was created, false means it already existed.
);
PushNotification.localNotification({
channelId: key, //this must be same with channelid in
createchannel
title: 'Local Message',
message: 'Local message !!',
})
};
export default LocalNotification
Now import the above file into App.tsx
import React from ‘react’;
import {
Button,
SafeAreaView,
ScrollView,
StatusBar,
Text,
useColorScheme,
View,
} from ‘react-native’;
import {
Colors,
} from ‘react-native/Libraries/NewAppScreen’;
import LocalNotification from ‘./Notification’;
function App(): React.JSX.Element {
const isDarkMode = useColorScheme() === ‘dark’;
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar
barStyle={isDarkMode ? ‘light-content’ : ‘dark-content’}
backgroundColor={backgroundStyle.backgroundColor}
/>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<View
style={{
backgroundColor: isDarkMode ? Colors.black :
Colors.white,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
alignContent: 'center',
}}>
<Text> Push Notification!! </Text>
<Button title={'Click Here'} onPress={LocalNotification}
/>
</View>
</ScrollView>
</SafeAreaView>
);
export default App;
Clicking on Click Here button will render a local
notification successfully.
Now moving onto Remote Notification Setup
For the android versions below 13 (that is 12 and 11
and below), notifications where enabled by default. But
from version 13 and above it is mandatory to ask
permission from the user to enable notification and the
notification is turned off (and blocked if the necessary
permissions are not present in the AndroidManifest.xml
file).
Add these few lines in PermissionsAndroid.js in
node_modules/react-native/Libraries/Permission
sAndroid/PermissionsAndroid.js
...
export type Rationale = {
...
POST_NOTIFICATIONS?: string,
};
const PERMISSION_REQUEST_RESULT = Object.freeze({
...
POST_NOTIFICATIONS: 'android.permission.POST_NOTIFICATIONS',
});
For our current project we have initialized this in
AndroidManifest.xml file already.
Create a file RemoteNotification.tsx and add the
following code line to configure the remote
notifications.
import { useEffect } from 'react';
import { PermissionsAndroid, Platform } from 'react-native';
import PushNotification from 'react-native-push-notification';
const checkApplicationPermission = async () => {
if (Platform.OS === 'android') {
try {
await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
);
} catch (error) {
console.error(error)
};
const RemoteNotification = () => {
useEffect(() => {
checkApplicationPermission();
// Using this function as we are rendering local
notification so without this function we will receive multiple
notification for same notification
// We have same channelID for every FCM test server
notification.
PushNotification.getChannels(function (channel_ids) {
channel_ids.forEach((id) => {
PushNotification.deleteChannel(id)
})
});
PushNotification.configure({
// (optional) Called when Token is generated (iOS and
Android)
onRegister: function (token) {
console.log('TOKEN:', token);
},
// (required) Called when a remote or local
notification is opened or received
onNotification: function (notification) {
const { message, title, id } = notification;
let strTitle: string =
JSON.stringify(title).split('"').join('');
let strBody: string =
JSON.stringify(message).split('"').join('');
const key: string =
JSON.stringify(id).split('"').join('');
PushNotification.createChannel(
channelId: key, // (required & must be unique)
channelName: "remote messasge", // (required)
channelDescription: "Notification for remote
message", // (optional) default: undefined.
importance: 4, // (optional) default: 4. Int
value of the Android notification importance
vibrate: true, // (optional) default: true.
Creates the default vibration patten if true.
},
(created) => console.log(`createChannel returned
'${created}'`) // (optional) callback returns whether the channel
was created, false means it already existed.
);
PushNotification.localNotification({
channelId: key, //this must be same with
channelId in createchannel
title: strTitle,
message: strBody,
});
console.log('REMOTE NOTIFICATION ==>', title,
message, id, notification);
// process the notification here
},
// Android only: GCM or FCM Sender ID
senderID: '1234567890'
popInitialNotification: true,
requestPermissions: true,
});
}, []);
return null;
};
export default RemoteNotification;
In this file we have create a function called
checkApplicationPermission . This function generally
requests the permission for the access to notification
which is by default not given to new application
installed in Android version 13+.
After getting the access for notification, we configure
PushNotification.configure in which we initially create a
device token onRegister which is necessary for a device
to receive remote notification.
The onNotification function is rendered when we
receive a notification. In our project particularly, we
are rendering a Local Notification when we are
receiving a remote notification as sometimes in
Foreground state we don’t receive a pop-up
notification. So in that case we are rendering such
functionality over here.
Receiving Remote Notification
Few more changes are needed to receive our remote
notification as we have 3 states of app activity:
1. Foreground State
2. Background State
3. Quit State
So for these states we are going to make changes in
App.tsx.
In App.tsx we are going import RemoteNotification and
render it.
import React from 'react';
import {
Button,
SafeAreaView,
ScrollView,
StatusBar,
Text,
useColorScheme,
View,
} from 'react-native';
import {
Colors,
} from 'react-native/Libraries/NewAppScreen';
import LocalNotification from './Notification';
import RemoteNotification from './RemoteNotification';
function App(): React.JSX.Element {
const isDarkMode = useColorScheme() === 'dark';
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar
barStyle={isDarkMode ? 'light-content' : 'dark-content'}
backgroundColor={backgroundStyle.backgroundColor}
/>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<View
style={{
backgroundColor: isDarkMode ? Colors.black :
Colors.white,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
alignContent: 'center',
}}>
<RemoteNotification />
<Text> Push Notification!! </Text>
<Button title={'Click Here'} onPress={LocalNotification}
/>
</View>
</ScrollView>
</SafeAreaView>
);
}
export default App;
Now after making all the above changes, we are
ready to receive our Remote Notification.
We will now head towards our FCM Console to
sender our notification.
To get Server Token, you have to firstly go to your
Firebase project, then go to Setting of your project then
navigate to Cloud Messaging. There you will see a
section called Cloud Messaging API (Legacy) which
will be disabled by default. Click Here to know how to
enable it & get Server Token
After clicking Push Notification, you will receive your
remote notification successfully.
Remote Notification Arrived
React Native Push Notification
In this tutorial, we’ve covered the essential steps to
integrate push notifications into your React Native
app using the react-native-push-notification package.
From setting up Firebase for notification services to
configuring local notifications, you now have a solid
foundation to implement push notifications effectively
in your projects.
As you continue to explore the vast possibilities of
React Native development, remember that push
notifications are a powerful tool for engaging users
and enhancing the user experience.
I hope this tutorial has provided you with valuable
insights and practical guidance on integrating push
notifications into your React Native projects. If you
have any questions or encounter any challenges along
the way, don’t hesitate to reach out to me for support.
Happy coding, and may your apps thrive with the
power of push notifications!