Reputation: 312
I'd like to integrate fcm in react js applicaiton to provide real time chat. Any inputs to proceed?
Upvotes: 2
Views: 9161
Reputation: 4421
I would suggest you take a look at this sample code. You may also want to take a look into the this video tutorial as well.
Upvotes: 2
Reputation: 1485
My answer is a short version of related article by Leonardo Cardoso. For details check his article.
Adding FCM to React app is pretty straightforward. I will demonstrate on project generated via create-react-app
.Of course, below instructions are feasible for all sort of react projects.
First of all, add Firebase
to project.
npm install firebase --save
Then, we are going to create js
file to hold logic of our push notifications. Let's name it push.js
and declare inside function to initialize firebase app
.
import firebase from 'firebase';
export const initializeFirebase = () => {
firebase.initializeApp({
// taken from your project settings --> cloud messaging
messagingSenderId: "your messagingSenderId"
});
}
We'll call this function in our entry point.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { initializeFirebase } from './push'; <-- add this
ReactDOM.render(<App />, document.getElementById('root'));
initializeFirebase(); <-- add this
In order to use firebase cloud messaging
, we need a service worker. By default, when you start Firebase
, it looks for a file called firebase-messaging-sw.js
. There is a way to create and attach your own service worker. For simplification, we'll use the default approach.
So, we need to add firebase-messaging-sw.js
to the location where our files are served. As we’re using the create-react-app, I’m going to add it inside the public folder with the following content:
importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase-app.js'); <-- check for last version
importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase-messaging.js'); <-- check for last version
firebase.initializeApp({
messagingSenderId: "your messagingSenderId again"
});
const messaging = firebase.messaging();
Initial setup is done. Now you can add functionality you want: ask for permission, send notification or any other. Implementation of asking permission and sending notification is described in the source article.
Upvotes: 7