Rose Chege Rose is a lover of technology and an upright individual who is not afraid to get out of her comfort zone and try out new programming paradigms.

React Native push notifications with Firebase Cloud Messaging

4 min read 1237

React Native uses JavaScript and React to build apps for iOS, Android, and the web from a single codebase. It also allows you to tap into the native features of each device, such as the device’s default themes, camera, geolocation, and push notifications. This means you can use React Native to build a complete mobile app that integrates with iOS or Android’s underlying settings, which makes it simple to implement push notifications, as I will demonstrate today.

In this article, we will learn how to build a simple React chat application that integrates with Firebase Cloud Messaging and the device’s push notifications to notify a user when they receive a new message.

Contents

Prerequisites

To follow along with this tutorial, it is essential to have the following:

  • Node v14 or above and npm v5.6 or above installed in your local machine
  • Working knowledge of React Native
  • A Firebase account

Setting up a React Native chat app

To set up the application, go ahead and create a project folder where you want your project to live, then initialize the application using this npx command:

npx react-native init chat_app_with_fcm

Once the above command is executed, a chat_app_with_fcm directory that hosts your React Native settings will be created. Change the directory path to the newly created chat_app_with_fcm folder:

cd chat_app_with_fcm

Let’s test if the bootstrapped React Native template is working. Make sure you have a connected device or an emulator, and then start the application as such:

npm run android

This will start a development environment that you can use to access the application on the connected device or emulator.

Building chat functionality

This guide is creating a chat application. To handle the chat functionality, we will use the react-native-gifted-chat package. The package will provide a ready-to-use, interactive UI for the chat application.

To install the package, open your project terminal and run the following command:

npm i react-native-gifted-chat

Once installed, navigate to the App.js file and make the following changes.

We made a custom demo for .
No really. Click here to check it out.

First, import the GiftedChat module:

import { GiftedChat } from 'react-native-gifted-chat'

Then, import the following Hooks:

import { useState, useCallback, useEffect } from "react";

Inside the App: () function, define a state for messages:

const [messages, setMessages] = useState([]);

Define a useEffect to set a default message when the application loads:

useEffect(() => {
    setMessages([
        {
            _id: 1,
            text: 'Hello there',
            createdAt: new Date(),
            user: {
                _id: 2,
                name: 'PartyA',
                avatar: 'https://placeimg.com/140/140/any',
            },
        },
    ]);
}, [])

Next, define an onSend event handler for when a user sends a message:

const onSend = useCallback((messages = []) => {
    setMessages(previousMessages => GiftedChat.append(previousMessages, messages)) // append the new message to present messages
}, [])

Finally, replace the rendered view with the GiftedChat component:

return (
    <GiftedChat
        backgroundColor={isDarkMode ? Colors.black : Colors.white}
        messages={messages}
        onSend={messages => onSend(messages)}
        user={{
            _id: 1,
        }}
    />
)

After making the above changes, React Native will use its hot reload features and reflect the changes to your screen.

chat_screen

Setting up an application on the Firebase console

Let’s now connect this application to Firebase. To set this up, log on to your Firebase account and create a new project using the Add project card. Enter your project name, and then click Continue. Feel free to enable or disable Google Analytics on the next step, and then click Continue.

When your project is ready, click Continue again to go to the project dashboard. On this dashboard, create an Android application using the Android icon present on your project dashboard.

Under Android package name, enter the package name from your app. You can get this package name inside the /android/app/src/main/AndroidManifest.xml file. Finally, hit Register app, download the google-services.json file, and place it under your project’s android/app/ directory.

Setting up Firebase Cloud Messaging in a React Native app

To connect our React Native application with Firebase, we have to configure the application with the Firebase credentials.

Under android/build.gradle, add the following classpath inside the buildscripts/dependencies tags:

classpath 'com.google.gms:google-services:4.3.10'

Under the /android/app/build.gradle file, add the google-services plugin right below apply plugin: "com.android.application" :

apply plugin: 'com.google.gms.google-services'

Next, install React Native Firebase like so:

npm i --save @react-native-firebase/messaging

These settings are ready. Now, let’s handle how React Native will use FCM to send the chat messages.

Handling foreground message notifications

First, create an event handler to handle foreground message notifications. The handler will receive the incoming message, structure it, add it to the message state, and display an alert.

Navigate to the App.js file and import React Native Firebase:

import messaging from '@react-native-firebase/messaging';

Under App(), add a useEffect() Hook, which will listen to any change in the messages state:

useEffect(() => {
}, [messages]);

Inside the useEffect(), add an event handler to listen to notifications:

// Get the notification message
const subscribe = messaging().onMessage(async remoteMessage => {

    // Get the message body
    let message_body = remoteMessage.notification.body;

    // Get the message title
    let message_title = remoteMessage.notification.title;

    // Get message image
    let avatar = remoteMessage.notification.android.imageUrl;

    // Append the message to the current messages state
    setMessages(messages => GiftedChat.append(messages, {
        _id: Math.round(Math.random() * 1000000),
        text: message_body,
        createdAt: new Date(),
        user: {
            _id: 2,
            name: "PartyB",
            avatar: avatar,
        },
    }));

    // Show an alert to the user
    Alert.alert(message_title, message_body);
});

return subscribe;

To test this, go to the Firebase console of the application you created in the previous step. On the left sidebar, under Engage, click Cloud messaging. Then click the button Send your first message.

On the form that proceeds:

  • Enter any title (e.g., “test”) Under Notification text
  • Type in “Hello there!” under Notification image
  • Paste in any image address you’d like, or use this one of a glass of water
  • Click the Next button below

Now, under Target, click Select an app and then select your app. Click Next on the next step and then Review. On the resulting popup, click Publish.

On the app, you should receive the following notification.

foreground notification

Handling background message notifications

Background message notifications work when the application is closed. Similarly to foreground notifications, we will be adding a handler.

To add the handler, make the following changes on App.js before App():

// Register background handler
// Get the notification
messaging().setBackgroundMessageHandler(async remoteMessage => {
    // Extract the body
    let message_body = remoteMessage.notification.body;
    // Extract the title
    let message_title = remoteMessage.notification.title;
    // Extract the notification image 
    let avatar = remoteMessage.notification.android.imageUrl;

    // Add the notification to the messages array
    setMessages(messages => GiftedChat.append(messages, {
        _id: Math.round(Math.random() * 1000000),
        text: message_body,
        createdAt: new Date(),
        user: {
            _id: 2,
            name: "PartyB",
            avatar: avatar,
        },
    }));

    // Send a notification alert
    Alert.alert(message_title, message_body);
});

To test the functionality, you will have to close the application, then send a notification message from the console as in the previous section.

You should receive such an alert like the one below on your phone’s push notification bar.

background notification

Conclusion

Notifications are critical to modern mobile applications. I hope this guide has helped you learn the important skill of adding push notifications to React Native apps. As we have seen, Firebase Cloud Messaging and React Native Firebase makes this flow seamless and very easy.

LogRocket: Instantly recreate issues in your React Native apps.

LogRocket is a React Native monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your React Native apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.

Start proactively monitoring your React Native apps — .

Rose Chege Rose is a lover of technology and an upright individual who is not afraid to get out of her comfort zone and try out new programming paradigms.

One Reply to “React Native push notifications with Firebase Cloud Messaging”

Leave a Reply