DEV Community

Cover image for Firebase Push notifications in React Native Apps
Abhijeet Rathore for Enappd

Posted on • Originally published at enappd.com

Firebase Push notifications in React Native Apps


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)


Yes, those …… are push notifications

One might wonder why to integrate Push notifications in an app. Following are the major reasons to use Push in your apps

  1. Stimulate user engagement with real time updates and reminders
  2. Re-engage/retain users — to activate those users who don’t use the app often
  3. Increase conversion rates — To convert users at the right time, as per your marketing campaigns
  4. Target the right users — By sending time-specific, location specific or even user specific messages/offers/reminders to users
  5. Track actionable metrics — by tracking users’ response to different types of reminders / offers
  6. Enhance brand consistency by sending brand’s logo inside push at regular intervals, depending on your marketing campaigns
  7. Improve your customer care strategy with useful content — to help users keep up with the latest updates, promotions, and offers inside the app
  8. 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.

React Native is a JavaScript framework for writing natively rendering mobile applications. It’ is based on React, Facebook’s JavaScript library for building user interfaces, but instead of targeting the browser, it targets mobile platforms. Because most of the code you write can be shared between platforms, React Native makes it easy to simultaneously develop for both Android and iOS.

React Native applications render using real mobile UI components, not webviews, and will look and feel like any other native mobile application. React Native also exposes JavaScript interfaces for platform APIs, so your React Native apps can access platform features like the phone camera, or the user’s location. Facebook, Palantir, TaskRabbit etc are already using it in production for user-facing applications.

Firebase

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
  • Analytics
  • Crashlytics
  • 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

Structure

I will go ahead in step-by-step fashion so you can follow easily.

  1. Create a Firebase project and find Push options
  2. Create a basic React Native app
  3. Install Push notification dependency
  4. Build the app on Android
  5. Send notifications from Firebase console
  6. 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


Your Firebase projects all in one place

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 !


Cloud messaging section of Firebase console — You can send push notifications from here

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.


Add a new Android app in Firebase

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)


Download google-services.json

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


Default start screen for React Native app

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

  1. react-native-push-notification
  2. react-native-firebase

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

In your android/build.gradle , edit the googlePlayServicesVersion and firebaseVersion . Following are the values in my (working) setup

ext {    
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

In your AndroidManifest.xml , add following before <application

and add these inside <application tag

Be careful while copy-pasting these values. Don’t disturb other values in the XML file.

3. Edit android/settings.gradle

In android/settings.gradle , add

...
include ':react-native-push-notification'
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

<resources>
<color name="white">#FFF</color>
</resources>

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 App.js

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


Push notification token in react-native debugger

Follow the steps in my blog — Complete guide on sending Push using Firebase Cloud Messaging Console to send notification.


Sending test push from Firebase console

Keep you app in any of these states

  • Foreground
  • Minimize (background)
  • Killed (closed)

You will receive the notification with a default icon, title and message, as I received like following

In Open App


Receiving push in foreground app

Yayyy ! We have successfully implemented push notification in a react-native app 🎉 🎉 🎉

In Closed App


Receiving push in closed app

In minimized app (background)


Receiving push in minimized app

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 App.js and PushController.js files 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.


Updating App with data received in 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 title and 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 title and message data once again in key-value pairs, and use that data in the app, instead of actual title and message . This is because we don’t know the app state when the data is received.


Sending the title and message as key-value pairs, if these are required in the app

Extra 🏆🏆🏆

Set application badge icon

PushNotification.setApplicationIconBadgeNumber(number: number)

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 PushNotification.localNotification()

Android Only Methods

PushNotification.subscribeToTopic(topic: string) Subscribe to a topic (works only with Firebase)

Checking Notification Permissions

PushNotification.checkPermissions(callback: Function) Check permissionscallback will be invoked with a permissions object:

  • alert: boolean
  • badge: boolean
  • sound: boolean

iOS Only Methods

PushNotification.getApplicationIconBadgeNumber(callback: Function) Get badge number

All these details can be studied better in the plugin’s Github repo.

Conclusion

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

Next Steps

Now that you have learnt about setting up Push Notifications in React Native apps, here are some other topics you can look into

If you need a base to start your next React Native app, you can make your next awesome app using React Native Full App

Top comments (0)