Creating Notifications in React Native With Firebase
Creating Notifications in React Native With Firebase
Welcome to this hands-on lab, where you will learn how to implement push notifications in a React Native application. You will be using Firebase Cloud Messaging
(FCM) to send and receive notifications. You will set up a simple app that can display notifications when it is received from Firebase Cloud Messaging.
Prerequisites
You need to have a Google account to create a Firebase database. This acocunt will be used for the Firebase project that you will create.
If you don't have a Google account please visit http://google.com to create one.
You need to have an Expo account as you will be using the Expo tools to create signed React Native mobile apps for Android and iPhone.
Objectives
After completing this lab, you will be able to:
cd myNotifications
3. Install all the packages that are required for your app.
4. Run the following command to set the the app to function from browser in addition to the app.
npx expo install react-native-web react-dom @expo/metro-runtime
6. Open the file App.js and paste the following content in it. The code registers to get notification and displays a notification that is received.
initializeApp requires Firebase app credentials to work. You will be providing these details later in the lab once you configure the app on Firebase.
// App.js
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import * as Notifications from 'expo-notifications';
import { initializeApp } from 'firebase/app';
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const app = initializeApp(firebaseConfig);
const App = () => {
useEffect(() => {
registerForPushNotificationsAsync();
const subscription = Notifications.addNotificationReceivedListener(notification => {
console.log('Notification received!', notification);
alert("There is a notification "+notification);
});
return () => {
subscription.remove();
};
about:blank 1/16
3/6/25, 12:10 AM about:blank
}, []);
const registerForPushNotificationsAsync = async () => {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
// Only ask if permissions have not already been granted
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
// Stop here if the user did not grant permission
if (finalStatus !== 'granted') {
alert('Notification permissions not granted!');
return;
}
// Get the device token
const token = (await Notifications.getExpoPushTokenAsync()).data;
console.log('Push Notification Token:', token);
// You can send this token to your server or Firebase Cloud Messaging for further processing
};
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Welcome to Firebase Messaging App!</Text>
</View>
);
};
export default App;
7. Install the Expo application services CLI. You will be using this later to generate the apk file.
3. Give your project a name such as reactnative-push-notification and check the box to agree to the terms and conditions regarding Firebase usage and click
Continue.
about:blank 2/16
3/6/25, 12:10 AM about:blank
4. You will see a screen which briefs on Google Analytics feature for your project. This is enabled by default. As you don't have the necessity to use Google Analytics
for the sample exercise, disable the option and click Create Project.
about:blank 3/16
3/6/25, 12:10 AM about:blank
5. You project will be prepared and be ready to use in a few seconds. Once ready, you will see a notification confirming the same. Click Continue to get started with
the project.
about:blank 4/16
3/6/25, 12:10 AM about:blank
Note: You can also add another iOS app with the same package name that you would be using for the Android app. For this lab, you will use just the Android
app.
7. Give a name for the app such as com.username.myNotifications. This has to be the same name as provided to the app that you created on Expo. Replace username
with your name and then click Register App.
about:blank 5/16
3/6/25, 12:10 AM about:blank
8. Download google-services.json and click Next. Place the file in your project within android/app folder.
about:blank 6/16
3/6/25, 12:10 AM about:blank
9. Click Next in the Add Firebase SDK section and proceed to the last section.
about:blank 7/16
3/6/25, 12:10 AM about:blank
1. Ensure that the app.json has the right application name. It would be as given below with your name reflecting in the placeholder username.
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff"
about:blank 8/16
3/6/25, 12:10 AM about:blank
},
"package": "com.username.myNotifications"
},
2. The updated content of ./android/build.gradle should be as below. Compare your changes with this code to ensure accuracy.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = findProperty('android.buildToolsVersion') ?: '35.0.0'
minSdkVersion = Integer.parseInt(findProperty('android.minSdkVersion') ?: '24')
compileSdkVersion = Integer.parseInt(findProperty('android.compileSdkVersion') ?: '35')
targetSdkVersion = Integer.parseInt(findProperty('android.targetSdkVersion') ?: '34')
kotlinVersion = findProperty('android.kotlinVersion') ?: '1.9.24'
ndkVersion = "26.1.10909125"
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath('com.android.tools.build:gradle')
classpath('com.facebook.react:react-native-gradle-plugin')
classpath('org.jetbrains.kotlin:kotlin-gradle-plugin')
classpath('com.google.gms:google-services:4.4.2') // Check for latest version
}
}
apply plugin: "com.facebook.react.rootproject"
apply plugin: "com.google.gms.google-services"
allprojects {
repositories {
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url(new File(['node', '--print', "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), '../android'))
}
maven {
// Android JSC is installed from npm
url(new File(['node', '--print', "require.resolve('jsc-android/package.json', { paths: [require.resolve('react-native/package.json')] })"
}
google()
mavenCentral()
maven { url 'https://www.jitpack.io' }
}
}
In the above script you have added the google-services plugin to the list of plugins and set the added the class path to the depndecies. Click here to see the changes.
3. Add the following plugin to ./android/app/build.gradle along with the other plugins that already exist.
apply plugin: "com.google.gms.google-services"
4. Copy the downloaded file google-services.json to the ./android/app/ directory. You can do this by using the upload option.
5. Run the following command in the terminal to generate the QR code for scanning and installing the application.
Note: Please note the number of builds in a month is restrited in the free tier.
eas build --profile preview -p android
about:blank 9/16
3/6/25, 12:10 AM about:blank
This will take a while. You will be prompted for creating a new package on expo, the first time you run it. Choose Yes. Once successful, a QR code is generated. You will
be prompted to Install and run the build on Android Emulator. Choose No as the Cloud IDE doesn’t have a simulator. You should expect to see an output as given
below.
You can scan the code on your phone with Expo Go app and follow the prompts to install the app in your phone. Make sure you turn the notifications on for your app.
If this expo build fails, open the build link that is given in the output above the error message. Expo free trial tier, is quiet slow and may sometimes lag in
response.
about:blank 10/16
3/6/25, 12:10 AM about:blank
3. Add a Notification title and Notification text as shown in the screenshot below. Then, click Next.
about:blank 11/16
3/6/25, 12:10 AM about:blank
4. Now, click the dropdown list and select the Android app that you just created.
about:blank 12/16
3/6/25, 12:10 AM about:blank
4. Schedule the message to be sent to eligible users to Now and click Next.
5. Enable Sound so that you can receive a notification when it is pushed to your phone and then click Review.
about:blank 13/16
3/6/25, 12:10 AM about:blank
8. You will receive a notification in about 2 to 5 minutes if everything is configured as expected. You will see the notification on your phone, as shown in the image
below.
about:blank 14/16
3/6/25, 12:10 AM about:blank
Practice Exercise
Remember, the notifications app will only work on actual device. It will only work on a device.
1. Go to https://snack.expo.dev/.
2. Add the following code to App.js.
import React, { useEffect, useState } from 'react';
import { Pressable, Text, View, Alert } from 'react-native';
import * as Notifications from 'expo-notifications';
// Set notification handler for foreground notifications
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
about:blank 15/16
3/6/25, 12:10 AM about:blank
shouldPlaySound: true,
shouldSetBadge: false,
}),
});
export default function App() {
const [notificationPermission, setNotificationPermission] = useState(false);
// Request permission for notifications on app load
useEffect(() => {
requestNotificationPermission();
}, []);
// Function to request notification permissions
const requestNotificationPermission = async () => {
const { status } = await Notifications.getPermissionsAsync();
if (status !== 'granted') {
const { status: newStatus } = await Notifications.requestPermissionsAsync();
setNotificationPermission(newStatus === 'granted');
} else {
setNotificationPermission(true);
}
};
// Function to send a notification
const sendNotification = async () => {
if (!notificationPermission) {
Alert.alert('Permission not granted', 'Please allow notifications to receive alerts.');
return;
}
await Notifications.scheduleNotificationAsync({
content: {
title: "Hello! 📬",
body: "This is a test notification",
sound: true,
},
trigger: { seconds: 2 }, // Notification will appear after 2 seconds
});
};
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Pressable
style={{'backgroundColor':'purple',
'borderRadius':10,
'margin':10,
'padding':15}}
onPress={sendNotification}>
<Text style={{'color':'white'}}>Send Notification</Text>
</Pressable>
</View>
);
}
3. You will see some errors on the bottom, for the missing dependencies. Click Add Dependency for each of the dependencies to be installed.
5. Once there are no errors, click on My Device and scan the QR code from the Expo Go app on your Android or iPhone.
6. When you press the button, you will receive a notification. You can use this to show the user notifications in an application as and when required.
Conclusion
Congratulations on completing this lab! You learned how to configure an app for firebase messaging and implement push notifications in a React Native application using
Firebase Cloud Messaging (FCM).
Author(s)
Lavanya T S
about:blank 16/16