If something real-time happens on your website, you want everyone to be alerted. It could be a new version, an announcement, or an update to a product. By utilizing Push Notifications, you can do that conveniently. The difference between a push notification and an SMS message is that a push notification does not cost anything to send.
However, most free push notification services offer limited functionality and a limited number of subscribers. Therefore, in this article, we are discussing the Google Firebase platform, which allows you to configure push notifications for free. Here, we’ll show you step-by-step how to implement Push Notifications with Firebase.
Are you excited? Let us begin by understanding why firebase.
Firebase – Why use it?
Google’s Firebase is an application development platform. In addition to offering a host of easily integrated features and functionalities, it helps to create backends for applications quickly. Firebase offers analytics, remote configurations, social logins, performance monitoring, email authentication, ad mob, and cloud messaging.
The use of messaging features can enhance user engagement. The Firebase notification integration service allows you to implement push notifications without hassle. With Firebase Cloud Messaging (FCM), you can implement messaging across multiple platforms simultaneously. In addition to iOS and Android, it is supported on the web, with Unity, and with C++ setups. Users can receive notifications or data messages using FCM.
Additionally, it can segment users and send different messages to different groups of users. Firebase can also be used to implement toast messages and other acknowledgement notifications. Messages can be triggered manually through user interaction using cloud functions for remote push notifications. To send and receive messages using FCM, the following components are required:
- Sending messages with Firebase requires an application server or cloud functions environment.
- Platform-specific client applications to receive messages.
As a result of using the notification tool, you can set up local notifications, remote notifications, test notifications, and React Native Push Notifications with ease. You can even go further by setting up an inbox to ensure messages are saved in a safe place.
However, are you wondering how to implement real-time alerts with react native push notifications? Then keep reading!
How to implement real-time alerts with react native push notifications?
React Native is a Facebook library for building front-end applications across multiple platforms. Google Firebase is a backend-as-a-service solution. The React Native Firebase tool combines these tools to build a cross-platform application. These notifications will aid you in updating your customers in real-time. Here are the steps on how to implement push notifications with firebase.
Step 1: Start a new Firebase project
Note: To begin a new project, go to the Firebase console. Modify the prompts according to your needs.
Step 2: Click on the Create a Project button.
Step 3: Click continue to name your project and accept Firebase’s terms.
Step 4: The final step is to choose a Google Analytics account to link with the project, select settings, and accept the terms. Click ‘create project’ to begin.
Step 5: Develop a React Native application
Additional Information: Follow the React documentation to create a React Native app.
$ react-native in it push Notifications Example
Here is a code snippet that you can use to run the Android application,
$ react-native run-android
Step 6:Push Notification Dependency
You can add push notification dependency to your React application using multiple packages. React-native-firebase adds all Firebase functionality to React applications. As you can see, we are using react-native-push-notification here, which is only concerned with push notifications.
In the case of NPM:
$ npm install –save react-native-push-notification
In the case of Yarn:
yarn add react-native-push-notification
Step 7: Make sure your application is registered
Using the Firebase dashboard, register your Android and/or iOS application. Using this example, we will implement push notifications only for Android apps.
Step 8: Create a name for your Android application
Add the google-services.json file to your application module’s root directory. Then, add the following code to the build.gradle file at the project level (<project>/build.gradle):
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google’s Maven repository
}
dependencies {
…
// Add this line
classpath ‘com.google.gms:google-services:4.3.8’
}
}
allprojects {
…
repositories {
// Check that you have the following line (if not, add it):
google() // Google’s Maven repository
…
}
}
With the following code snippet from the Firebase documentation, create the project-level
build.gradle (#project>/#app-module#/#build.gradle)
apply plugin: ‘com.android.application’
// Add this line
apply plugin: ‘com.google.gms.google-services’
dependencies {
// Import the Firebase BoM
implementation platform(‘com.google.firebase:firebase-bom:28.2.1’)
// Add the dependencies for the desired Firebase products
// https://firebase.google.com/docs/android/setup#available-libraries
}
The following code should be added to AndroidManifest.xml,
<uses-permission android:name=”android.permission.WAKE_LOCK” />
<permission
android:name=”${applicationId}.permission.C2D_MESSAGE”
android:protectionLevel=”signature” />
<uses-permission android:name=”${applicationId}.permission.C2D_MESSAGE” />
<uses-permission android:name=”android.permission.VIBRATE” />
<uses-permission android:name=”android.permission.RECEIVE_BOOT_COMPLETED”/>
<application …….>
<meta-data android:name=”com.dieam.reactnativepushnotification.notification_channel_name”
android:value=”YOUR NOTIFICATION CHANNEL NAME”/>
<meta-data android:name=”com.dieam.reactnativepushnotification.notification_channel_description”
android:value=”YOUR NOTIFICATION CHANNEL DESCRIPTION”/>
<meta-data android:name=”com.dieam.reactnativepushnotification.notification_color”
android:resource=”@android:color/white”/>
<receiver
android:name=”com.google.android.gms.gcm.GcmReceiver”
android:exported=”true”
android:permission=”com.google.android.c2dm.permission.SEND” >
<intent-filter>
<action android:name=”com.google.android.c2dm.intent.RECEIVE” />
<category android:name=”${applicationId}” />
</intent-filter>
</receiver>
<receiver android:name=”com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher” />
<receiver android:name=”com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver”>
<intent-filter>
<action android:name=”android.intent.action.BOOT_COMPLETED” />
</intent-filter>
</receiver>
<service android:name=”com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService”/>
<service
android:name=”com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService”
android:exported=”false” >
<intent-filter>
<action android:name=”com.google.firebase.MESSAGING_EVENT” />
</intent-filter>
</service>
… </application>
Make sure the code is synchronized.
Step 9: Implement the push functionality
To configure PushNotification.configure, use the following code. The code must be written in a separate JS file and imported into App.js.
import React, {Component} from “react”;
import PushNotification from “react-native-push-notification”;
// var PushNotification = require(“react-native-push-notification”);
export default class PushController extends Component{
componentDidMount(){
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) {
console.log(“NOTIFICATION:”, notification);
// process the notification here
// required on iOS only
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// Android only
senderID: “1090501687137”,
// iOS only
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
requestPermissions: true
});
}
render(){
return null;
}
}
This is what the App.js file looks like when you open it:
import React, { Fragment } from ‘react’;
import PushController from ‘./PushController’;
import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, FlatList} from ‘react-native’;
import {Header, LearnMoreLinks, Colors, DebugInstructions, ReloadInstructions } from ‘react-native/Libraries/NewAppScreen’;
// Dummy data for list, we’ll replace this with data received from push
let pushData = [
{
title: “First push”,
message: “First push message”
},
{
title: “Second push”,
message: “Second push message”
}
]
_renderItem = ({ item }) => (
<View key={item.title}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.message}>{item.message}</Text>
</View>
);
const App = () => {
return (
<Fragment>
<StatusBar barStyle=”dark-content” />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior=”automatic”
style={styles.scrollView}>
<Header />
<View style={styles.listHeader}>
<Text>Push Notifications</Text>
</View>
<View style={styles.body}>
<FlatList
data={pushData}
renderItem={(item ) => this._renderItem(item)}
keyExtractor={(item ) => item.title}
/>
{/* <LearnMoreLinks /> */}
</View>
</ScrollView>
</SafeAreaView>
<PushController/>
</Fragment>
);
};
const styles = StyleSheet.create({
scrollView: {backgroundColor: Colors.lighter,},
listHeader:{ backgroundColor: ‘#eee’, color: “#222”, height: 44, padding: 12},
title:{fontSize: 18, fontWeight: ‘bold’, paddingTop: 10},
message:{ fontSize: 14, paddingBottom: 15, borderBottomColor: “#ccc”, borderBottomWidth: 1},
engine: { position: ‘absolute’, right: 0,},
body: { backgroundColor: Colors.white, paddingHorizontal: 20, paddingVertical: 10, },
sectionContainer: { marginTop: 32, paddingHorizontal: 24, },
sectionTitle: { fontSize: 24, fontWeight: ‘600’, color: Colors.black},
sectionDescription: { marginTop: 8, fontSize: 18, fontWeight: ‘400’, color: Colors.dark,},
highlight: { fontWeight: ‘700’},
footer: { color: Colors.dark, fontSize: 12, fontWeight: ‘600’, padding: 4, paddingRight: 12, textAlign: ‘right’,},
});
export default App;
import React, { Fragment } from ‘react’;
import PushController from ‘./PushController’;
import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, FlatList} from ‘react-native’;
import {Header, LearnMoreLinks, Colors, DebugInstructions, ReloadInstructions } from ‘react-native/Libraries/NewAppScreen’;
// Dummy data for list, we’ll replace this with data received from push
let pushData = [
{
title: “First push”,
message: “First push message”
},
{
title: “Second push”,
message: “Second push message”
}
]
_renderItem = ({ item }) => (
<View key={item.title}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.message}>{item.message}</Text>
</View>
);
const App = () => {
return (
<Fragment>
<StatusBar barStyle=”dark-content” />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior=”automatic”
style={styles.scrollView}>
<Header />
<View style={styles.listHeader}>
<Text>Push Notifications</Text>
</View>
<View style={styles.body}>
<FlatList
data={pushData}
renderItem={(item ) => this._renderItem(item)}
keyExtractor={(item ) => item.title}
/>
{/* <LearnMoreLinks /> */}
</View>
</ScrollView>
</SafeAreaView>
<PushController/>
</Fragment>
);
};
const styles = StyleSheet.create({
scrollView: {backgroundColor: Colors.lighter,},
listHeader:{ backgroundColor: ‘#eee’, color: “#222”, height: 44, padding: 12},
title:{fontSize: 18, fontWeight: ‘bold’, paddingTop: 10},
message:{ fontSize: 14, paddingBottom: 15, borderBottomColor: “#ccc”, borderBottomWidth: 1},
engine: { position: ‘absolute’, right: 0,},
body: { backgroundColor: Colors.white, paddingHorizontal: 20, paddingVertical: 10, },
sectionContainer: { marginTop: 32, paddingHorizontal: 24, },
sectionTitle: { fontSize: 24, fontWeight: ‘600’, color: Colors.black},
sectionDescription: { marginTop: 8, fontSize: 18, fontWeight: ‘400’, color: Colors.dark,},
highlight: { fontWeight: ‘700’},
footer: { color: Colors.dark, fontSize: 12, fontWeight: ‘600’, padding: 4, paddingRight: 12, textAlign: ‘right’,},
});
export default App;
You can find the Sender ID and other authentication details under the Cloud Messaging section of the project settings.
Step 10. Install and run the Android app
Using the following code snippet, you can run the Android application you built in the previous steps:
$ react-native run-android
Step 11: Make use of FCM to send push notifications
Compose and select targets for the push notification by following the prompts.
If you wish, you can schedule the message for a later time or send it right away.
Step 12: You can modify additional options according to your needs. Click the review button. In the following popup, click the publish button to send the message according to your settings.
A push notification will be sent to the application on the schedule based on the targeting criteria. For advanced push notification functionality, cloud functions can be used.
Conclusion
It is our hope that this article will help you create and send real-time alerts with React Native Push Notifications. The use of push notifications can enhance your customer experience. However, if all of this seems tiring to you, you can use WonderPush Push Notifications Provider. You will be able to create push notifications much more conveniently with this platform.