In this post, we’ll learn how to setup Push notification in React Native apps using Firebase. We’ll send notification using Firebase console and receive them in the app. We will also learn how to handle push notifications in your React Native apps. By handling, I mean how to access the data sent via the notification inside your app, and wake your app up if it is asleep or closed.
Because all this can get reallllly long, I’ll limit the discussion to Android apps alone. I will post another blog for push in iOS apps in React Native. (Really, the major difference is in setting up the push certificates for iOS app, that’s all)
Complete source code of this tutorial is available here — React-Native-Push-Example
What are Push Notifications
How do you know when you get a new message on Whatsapp, Facebook or Twitter, if the app is closed, or even when it is open? Yes, those small messages that pop down from the top of the screen like banners, showing new messages, updates or news are called Push notifications (or simply Push)
One might wonder why to integrate Push notifications in an app. Following are the major reasons to use Push in your apps
- Stimulate user engagement with real time updates and reminders
- Re-engage/retain users — to activate those users who don’t use the app often
- Increase conversion rates — To convert users at the right time, as per your marketing campaigns
- Target the right users — By sending time-specific, location specific or even user specific messages/offers/reminders to users
- Track actionable metrics — by tracking users’ response to different types of reminders / offers
- Enhance brand consistency by sending brand’s logo inside push at regular intervals, depending on your marketing campaigns
- Improve your customer care strategy with useful content — to help users keep up with the latest updates, promotions, and offers inside the app
- Reduce efforts in the customer journey- by using deep links in push messages that direct users to a certain place in your app
You can read more details of this in rubygarage blog
What is React-Native
TLDR; — React Native (RN) apps are more “native” than webview apps made by Cordova / Ionic. But React Native is yet to release a stable (1.0.0_) version of the framework.
Firebase is a Backend-as-a-Service (BaaS) platform. It started as a YC11 startup and grew up into a next-generation app-development platform on Google Cloud Platform. It is getting popular by the day because of the ease of integration and variety of functionalities available on it.
Some of the quick integrations available with Firebase are
- Email Authentication
- Social logins
- Real-time database
- Push notifications ⬅️
- In-app messages
- Remote config
and much more. Firebase is quickly growing to become the most popular mobile app back-end platform.
Enough of story-telling, let’s dive into — How to implement Push notification in React Native apps
I will go ahead in step-by-step fashion so you can follow easily.
- Create a Firebase project and find Push options
- Create a basic React Native app
- Install Push notification dependency
- Build the app on Android
- Send notifications from Firebase console
- Handle different type of Push notifications in your app
1. Create a Firebase project and find Push options
Go to Firebase and create your first project (or use an existing one). Your console should look like this
Note — It’s really easy to create a Firebase project, but if you still face any issue, follow step 1–4 of this blog
Click on your project and you’ll enter the project’s dashboard. Look for Cloud Messaging tab. This is where the magic will happen !
Push Notifications Settings
Firebase console also contains push notifications settings for web, android and iOS. Here you can find your sender_id, upload iOS push certificates etc. For setting up options, you’ll first have to create an Android app in Firebase console.
During the process, it will ask you to enter app’s package name and provide google-services.json. Make sure you keep the package name unique and consistent. (If we create a new project called “HelloWorld” using react native CLI, by default package name for android project will be “com.helloworld” and default bundle identifier for iOS app will be “org.reactjs.native.example.HelloWorld”., don’t use the default package name)
2. Create a basic React Native app
First, make sure you have all pre-requisites to create a react-native app as per the official documentation.
At the time of this post, I have React-Native version 0.60
Create a blank react-native app (Replace
myApp with your own name)
$ react-native init myApp
This will create a basic React-native app which you can run in a device or simulator. (either Android or iOS)
Let’s run the app in Android using
$ react-native run-android
You’ll see the default start screen
Change the UI of this front page by changing
app.js and the page will look like this
We’ll update this list with Push Notification content as we receive them. I’m not using any native storage etc. so the list will refresh on each app restart.
3. Install Push notification dependency
There are two major dependency / plugin you can use to implement push notifications
react-native-firebase is a major plugin that can implement almost all Firebase functionalities in react-native. But for this tutorial, we’ll use react-native-push-notification plugin, which is made only for Push Notification purpose.
Install the dependency using
$ npm install --save react-native-push-notification
Since I am using react-native 0.60, I don’t need to manually link dependencies. This is automatically done while building app for a platform.
Important: Follow the setup steps for this plugin very carefully. These may change slightly with time, but majority steps will remain common and you’ll know where to correct things if you face any error. At present, I am working with RN-0.60.4, react-16.8.6, and Android-28.
1. Edit android/build.gradle
android/build.gradle , edit the
firebaseVersion . Following are the values in my (working) setup
buildToolsVersion = "28.0.3"
minSdkVersion = 16
compileSdkVersion = 28
targetSdkVersion = 28
supportLibVersion = "28.0.0"
googlePlayServicesVersion = "16.1.0" // default: "+"
firebaseVersion = "17.3.4" // default: "+"
2. Edit AndroidManifest.xml
AndroidManifest.xml , add following before
and add these inside
Be careful while copy-pasting these values. Don’t disturb other values in the XML file.
3. Edit android/settings.gradle
android/settings.gradle , add
project(':react-native-push-notification').projectDir = file('../node_modules/react-native-push-notification/android')
4. Create a Color resource
In step 3.2 above, we called for a
white color as the notification_color. If that does not exist in your project, create it. You can also change this to any color you want. Create the
android/app/src/res/values/colors.xml file if it does not exist
5. Implement push functionality in your app
To implement push, we need to call
PushNotification.configure at our app start. This command initializes the push functionality in the app. I will create a separate file for this
PushController.js, and import it in
There are quite a few things going on here
- onRegister — is called when the application registers itself on Push server and obtains a token. It works both in iOS and Android.
- onNotification — is actually the heart of the functionality. This is called when a push is received and tapped. This method also receives the whole notification data, which is printed in the code above.
- senderID — is the cloud messaging sender ID from Firebase console
- permissions — allows certain permissions in iOS
In short, when your app starts, we’ll register the app and receive a token as a proof of registration. Also, when notification is received, we’ll receive the data via onNotification method.
Import this file in
App.js and include it in the code. Since it is returning
null , it won’t affect the layout. The
App.js will look like this
This implements push functionality in the app. Now we’ll build this app for Android and test.
4. Build the app on Android
Building on android is fairly easy. Make sure you have all pre-requisites to build a react-native app as per the official documentation. For push notification testing, we’ll need to build the app on a physical device. My current Android Studio version is 3.4.0 with Android 28.
Build the app for android using
$ react-native run-android
This will build and run the app on your connected device. If you face any issue during build, check for the errors in this troubleshooting guide for the plugin, or comment below the post. I’ll try my best to respond quickly.
5. Send notifications from Firebase console
Prepare a simple push notification from Firebase console and send it to all connected devices (which should ideally be only your test device), or send it using the token you receive in debugger. The token looks like this
Follow the steps in my blog — Complete guide on sending Push using Firebase Cloud Messaging Console to send notification.
Keep you app in any of these states
- Minimize (background)
- Killed (closed)
You will receive the notification with a default icon, title and message, as I received like following
In Open App
Yayyy ! We have successfully implemented push notification in a react-native app 🎉 🎉 🎉
In Closed App
In minimized app (background)
6. Handle different type of Push notifications
In last section, we saw a notification received in open, closed and minimized app. Let’s see how to receive data from these notification and populate our list.
For foreground app
We can check the push data format in debugger. E.g. this is a notification received in foreground app
You can see we receive all the required data in the notification object, namely — id, title, message, userInteraction and extra data sent as key-value pair
We can use this data to populate the list we have. In a practical application, you can do a lot of stuff using these data values.
I have modified the
PushController.jsfiles a bit to accept incoming push notification data. Please check the Github repo if you are stuck
Essentially I am storing the list items’ data in
this.state.pushData and updating it as we receive push.
Note: Push notification data in Foreground is available as soon as the push arrives. If you tap the notification again, the data will come to the app again. This can lead to duplication.
For close and background app
When the app is closed or in background, the data received is in slightly different format. We don’t receive the
message fields of the notification, but we do receive all the custom key-value pairs sent with the notification.
Hence, it is advised to send the
message data once again in key-value pairs, and use that data in the app, instead of actual
message . This is because we don’t know the app state when the data is received.
Set application badge icon
Works natively in iOS. Uses the ShortcutBadger on Android, and as such will not work on all Android devices.
Sending Notification Data From Server
Same parameters as
Android Only Methods
PushNotification.subscribeToTopic(topic: string) Subscribe to a topic (works only with Firebase)
Checking Notification Permissions
PushNotification.checkPermissions(callback: Function) Check permissions
callback will be invoked with a
iOS Only Methods
PushNotification.getApplicationIconBadgeNumber(callback: Function) Get badge number
All these details can be studied better in the plugin’s Github repo.
In this post, we learnt how to implement Push notifications using Firebase in React native apps. We also learnt how to handle different types of push and use their data in the app.
Complete source code of this tutorial is available here — React-Native-Push-Example
Now that you have learnt about setting up Push Notifications in React Native apps, here are some other topics you can look into
- React Native life cycle hooks
- How To in React Native — Image picker | Integrate Firebase
- Create Awesome Apps in React Native using Full App
If you need a base to start your next React Native app, you can make your next awesome app using React Native Full App
React Native without Expo
Pablo Díaz Márquez -
How to support Split View on iPad with React Native
Takuya Matsuyama -
Generate release mode APK for React-Native project to publish on PlayStore
Zilu Ramkrishna Rane -
What I learned trying to connect Firebase to an app with React and Redux
Jaime Rios -