Saturday, November 23, 2024
- Advertisment -
HomeComputersHow to Implement React Native Push Notification using Firebase

How to Implement React Native Push Notification using Firebase

Introduction

Developing the application whether it is a web or mobile app,  isn’t easy from scratch. However, it is true online software can help you build an app without putting your hands into coding. But the app is not only about coding; it needs a creative mind, robust UX, and UI that better engagement. 

So, if you’re interested in creating an app that demands easy efforts, try Firebase. Let’s dive deeper and know how Firebase can help and good move to implement React Native push notifications

What is Firebase?

It is an application development platform that works as a backend quickly and helps to create built-in features and functionalities in a host, which can be integrated easily. Additionally, it is good to enhance user engagement. 

Some cool features of Firebase are:

  • Analytics
  • Remote configurations
  • Social logins
  • Performance monitoring
  • Email authentication
  • Ad mod
  • Cloud messaging

Why Firebase for React Native Push Notifications?

Firebase is a cloud messaging solution that can implement React Native push notifications easily. This has the power to enhance user engagement, and that’s what you need. Additionally, it supports Android, Unity, and C++ setups. Plus, messages are triggered manually with the help of CRON jobs. 

Let’s dive and see how to implement React Native Push Notifications with Firebase!

Step-By-Step Guide to Implement React Native Push Notifications

Step 1- Create a New Firebase Project

  • Launch the Firebase console and click on a new project.
  • Enter the details of your project 
  • Accept the terms and conditions of Firebase to proceed further
  • The next step is to sync your Google Analytics account with the project
  • Go to settings and accept the terms, and tap on creating a project

Step 2- Create React Native App

  • Create your app according to React Native push notifications documentation

 $ react-native init pushNotifExample

  • Run the Android application with a code snippet

$ react-native run-android

Step 3- Push Notification Dependency

You can use multiple packages to add push notification dependency to react-native. However, react-native Firebase is the popular package you can add to your firebase functionalities to react applications. 

Some packages you can use are:

For npm-

$ npm install –save react-native-push-notification

For yarn-

yarn add react-native-push-notification

 Step 4- Register Your App

  • Go to Firebase dashboard
  • Register your android/iOS app

Here we are considering an example that deals with implementing push notifications on android apps. 

  1. Register Android app with the name
  2. Next, download the Google services.json file and save it under the root directory of your application module.
  3. Try the given code- (<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

}

}

 You can even create the application level with code- build.grade (<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

}

Now add the given code 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>

Next sync the code.

Step 5- Implement Push Notification Functionality

With the following code call push notification.configure from the start of the app.

Note- it should be written separately JS file and imported to 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;

}

}

The app code will look like this-

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;

Here under the project settings, sender ID, as well as authentication details, can be accessed.

Step 6- Run The App

With the following code snippet, you can run the application.

$ react-native run-android

Step 7- Send Push Notification with FCM

  • Go to firebase dashboard 
  • Navigate engage > cloud messaging 
  • Compose messages, choose targets and send push notifications.

You can customize push notifications according to your choice. You can even send notifications according to target. 

Final Words

That’s all! Finally, you have learned the steps to implement react native push notifications using firebase. Once you implement them, you can access the notifications with ease. You can use WonderPush to implement customized push notifications. 

Syandita Malakar
Syandita Malakar
Hi guys this is Syandita. I started Business Module Hub to help you all to post updated articles on technologies, gadgets. Although I love to write about travel, food, fashion and so on. I quite love reading the articles of Business Module Hub it always update me about the new technologies and the inventions. Hope you will find Business Module Hub interesting in various way and help you accordingly. Keep blogging and stay connected....!
RELATED ARTICLES
- Advertisment -

Most Popular

- Advertisement -

All Categories

- Advertisment -