Push Notifications in ReactJS with OneSignal
Tags: react, javascript, webdev, frontend
Published: 2021-01-25 01:08:50

In this tutorial, you are going to learn how to communicate with the users of your application by integrating push notifications and subscriptions into your ReactJS application using OneSignal. 

<h2>Topics covered in this tutorial</h2>

- ReactJS
- Push Notifications
- OneSignal Segments
- Audience
- Subscriptions
- One Signal's SDK

Before we begin, it's important to define what a push notification is.

<h2>What is a Push Notification?</h2>

Push notifications are clickable pop-up messages that appear on your users’ browsers irrespective of which device they use or which browser they are on. Subscribers can be anywhere on the browser and still receive these messages even if the website or app are not running.

Browser push notifications are different from in-app notifications because in-app notifications appear only when triggered by an existing application on your mobile device; browser push notifications can be triggered through browsers on any device as long as the user subscribes to receive your notifications. It is an instant mode of automated, direct communication between a website and its end users. 

<h2>Time to get our hands dirty!!! 🎊</h2>

In this tutorial, we are going to use OneSignal to send the push notifications and handle the subscriptions.

<i>OneSignal is the market leader in customer engagement, powering mobile + web push, email, SMS & in-app messages.</i>

The first thing that we have to do is to create an account inside of <a href="https://onesignal.com/">OneSignal</a>

1) Once you have created an account, you will create a new application

![OneSignal React](https://dev-to-uploads.s3.amazonaws.com/i/5yotjpw61gjafolh46fy.png)

2) When creating the app, you can give it whatever name you want. Make sure sure the "No Organization" option is selected from the organizations dropdown. Lastly, click on Web Push and click <strong>NEXT</strong>.

![OneSignal React](https://dev-to-uploads.s3.amazonaws.com/i/gyx66uy5zprn0jtobiva.png)

3) Configure your Web Push by entering the website's name and by entering the site's URL then click <strong>SAVE</strong>.

<i>Notes</i>

<i>-Keep in mind that your application has to be hosted in a server for the Push Notifications to work. If you want to deploy your website in a quick and easy way, follow <a href="https://dev.to/thisdotmedia/web-app-deployment-with-firebase-in-2-minutes-4bo8">this</a>  2min tutorial.</i> 

<i>-You can enter a default URL icon but this is an option, not mandatory</i>.

![OneSignal](https://dev-to-uploads.s3.amazonaws.com/i/6fxe2rvvhsbf3coib32m.png)

4) Download the SDK files and save them in a place you will remember in your computer because we are going to use them later on.

<i>The .zip file you are downloading contains 2 files. These are the Service Workers provided by OneSignal. To learn more about Service Workers in general read <a href="https://dev.to/thisdotmedia/intro-to-pwa-and-service-workers-15d4">this</a> article.</i>

<strong>DO NOT CLOSE THE CONFIG PAGE. WE WILL BE BACK TO IT SOON.</strong>

<h2>Integrating OneSignal To Your ReactJS App</h2>

Feel free to clone the repo with the basic structure of the React application where we will integrate OneSignal or follow the steps given in this tutorial to integrate OneSignal into your own React application.

<h3>Github repo</h3>

https://github.com/devpato/onesignal-demo
 
-initial state branch (INIT)
-final code branch (MAIN)

5) Inside of the React project, the first thing you are going to do is to add the services worker files you downloaded into your <strong>PUBLIC</strong> folder.

You should be adding 2 files:

- OneSignalSDKUpdaterWorker.js
- OneSignalSDKWorker.js

![OneSignal React](https://dev-to-uploads.s3.amazonaws.com/i/7d7cpa213fzer286v3xy.png)

6) In the same folder (PUBLIC) you have a file called <strong>Index.html</strong>. Go to that file and paste the following line of code inside of you ``<head></head>`` tag.

 ```html 
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
```

Your file should look something like <a href="https://github.com/devpato/onesignal-demo/blob/main/public/index.html">this</a>:

```html
<head>
.
.
.
  <title>One Signal - React</title>
  <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
</head>
```


7) Open the App.js file located inside of the <strong>SRC</strong> folder and paste the code 

```javascript
  window.OneSignal = window.OneSignal || [];
  const OneSignal = window.OneSignal;
```

This code will allows us to have access to the OneSignal object that we injected into our app thanks to the SDK we added in the <strong>index.html</strong> file.

8) In the same file, inside of the ``useEffect`` add the following code:

```javascript
OneSignal.push(()=> {
      OneSignal.init(
        {
          appId: "1a9bbed2-9294-4192-a736-01b461cb389a", //STEP 9
          promptOptions: {
            slidedown: {
              enabled: true,
              actionMessage: "We'd like to show you notifications for the latest news and updates about the following categories.",
              acceptButtonText: "OMG YEEEEESS!",
              cancelButtonText: "NAHHH",
              categories: {
                  tags: [
                      {
                          tag: "react",
                          label: "ReactJS",
                      },
                      {
                        tag: "angular",
                        label: "Angular",
                      },
                      {
                        tag: "vue",
                        label: "VueJS",
                      },
                      {
                        tag: "js",
                        label: "JavaScript",
                      }
                  ]
              }     
          } 
        },
        welcomeNotification: {
          "title": "One Signal",
          "message": "Thanks for subscribing!",
        } 
      },
        //Automatically subscribe to the new_app_version tag
        OneSignal.sendTag("new_app_version", "new_app_version", tagsSent => {
          // Callback called when tag has finished sending
          console.log('new_app_version TAG SENT', tagsSent);
        })
      );
    });
```
Let's talk about the previous code. The OneSignal object can only be initialized once ``.init()``. In this example we are triggering the initialization as soon as the App component loads. 

The ``promptOptions`` property will hold all the information related to the <a href="https://documentation.onesignal.com/docs/permission-requests"> prompt message </a> we are displaying to the user.

slidedown property is the type prompt that will slide down from the top of your page. This type of prompt has multiple properties you can use to customize it. Let's take a look to some of those properties:

-actionMessage: This is the main message to display in the prompt.

-acceptButtonText: Text for the accept button inside of the prompt.

-cancelButtonText: Text for the cancel button inside of the prompt.

![OneSignal React](https://dev-to-uploads.s3.amazonaws.com/i/iqhwdixo65ibdj06o3cb.png)

categories: Property that takes an array of tags. The <a href="https://documentation.onesignal.com/docs/slide-prompt#category-tags">Category Slidedown</a> works just like the regular Slide Prompt except it also allows subscribers to opt-in or opt-out of notification categories set as Data Tags.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wypcvjp05oi05gfkb598.png)

welcomeNotification: Displays a in-app notification after we have clicked on the accept button inside of the prompt and after the user has allowed the notifications in the app and after.

Finally, at the bottom of the code provided above, you will see the following code:

```javascript
OneSignal.sendTag("new_app_version", "new_app_version", tagsSent => {
   console.log('new_app_version TAG SENT', tagsSent);
})
```
<a href="https://documentation.onesignal.com/docs/data-tag-implementation#sdk-tagging-methods">sendTags</a> will send a tag to OneSignal specifying the tag the users belong too. We can use these tags to target users by creating segments for things like marketing campaigns. The cool thing about sendTag is that you can use this method in other parts of your app without the need of a prompt. For example you can use them on a click of a button. 

9) Now, let's go back to the configuration page inside the OneSignal website. Once you are in there, you are going to copy the <i>appId</i> inside of the "Add code to site" section. Your app ID is unique per application. If you try to use mine, it won't work.

![OneSignal](https://dev-to-uploads.s3.amazonaws.com/i/n8coi256xi4fhht5mz54.png)

After you have copied the appId, go back to your App.js file inside of your ReactJS app and inside of the OneSignal object assign your copied appId to the appId property.

10) Now build you app and deploy it to your server.

<h3>YAY! we are done with the code part!</h3>

11) Navigate to your app's website. You should see the following:

![OneSignal](https://dev-to-uploads.s3.amazonaws.com/i/kkqkpo57dprfcmesyyn7.png)

-Click on Allow on the OneSignal prompt

After you have clicked allow on the OneSignal prompt we will see this browser message

![OneSignal](https://dev-to-uploads.s3.amazonaws.com/i/p1av7crv0kpzp7tydtwi.png)

Click "Allow" and you will see the in-app (welcomeNotification)

![OneSignal React](https://dev-to-uploads.s3.amazonaws.com/i/85m2ihxgatlu8e8z79oq.png)

<h2>The OneSignal Platform</h2>

12) Let's go back to the OneSignal website. We are going to create a new <a href="https://documentation.onesignal.com/docs/segmentation">Segment</a> to target specific users for our marketing campaign.

On the top navigation bar of the website, click where it says "audience". Once you are in that section, click the blue button that says "New Segment"

![OneSignal](https://dev-to-uploads.s3.amazonaws.com/i/61sjul9hxjf8uvsc58ci.png)

A modal as the following will appear

![OneSignal](https://dev-to-uploads.s3.amazonaws.com/i/xtgqnfgq0olot0qakc35.png)

Enter whatever name you want for you Segment and click on "User tag".

![OneSignal React](https://dev-to-uploads.s3.amazonaws.com/i/atql60ln12ktmvq6mif5.png)

Create the user segments rules. Once you are done, click on the blue button "Create Segment".

<h3>YAY! you have officially created you first Segment.</h3>

<h2>Time to test our application!</h2>
 
13) We are going to create our first Push Notification using OneSignal. Navigate to Messages and click on the blue button "New Push".

![OneSignal React](https://dev-to-uploads.s3.amazonaws.com/i/rfubtltq7j7ij14ld9mt.png)

In the "Audience" section select "Send to Particular Segment(s)". Remove the segment of "Subscribed Users" and add the Segment you just created.

![OneSignal React](https://dev-to-uploads.s3.amazonaws.com/i/z2grbfw8l82prox0hc3j.png)

For the "Message" section enter the title, message, and icon you want the Push notification to have.

![OneSignal React](https://dev-to-uploads.s3.amazonaws.com/i/ata48hg1k0xju9z1pxc9.png)

Lastly, in the "Schedule" section select "Begin sending immediately" and "Send immediately" and click on the blue button "Confirm"

![OneSignal React](https://dev-to-uploads.s3.amazonaws.com/i/qkjrbimxxos4llm4d0b1.png)

Review your message before sending and click "Send message" and see the magic happening :)

![OneSignal React](https://dev-to-uploads.s3.amazonaws.com/i/e1uviep6se76o6uwahox.png)

You will receive see your first Push notification coming from OneSignal!

![OneSignal](https://dev-to-uploads.s3.amazonaws.com/i/sbw66gmadezddvirknnj.png)

<h2>Conclusion</h2>

OneSignal is a great tool to interact with the application's users. OneSignal is a great communication tool. This tool allows you not only to send Push notifications but also to target specific segments of users you want to interact with. OneSignal has a great Dashboard where you can keep track of how your users are interacting with your Push notifications or any other tool inside of OneSignal used to communicate with the users like SMS, emails, and more. I have used other technologies to send Push notifications and from my point of view, OneSignal was the one that was the easiest to integrate into your website. You can integrate it to a regular HTML/CSS/JS website with almost no programming experience.

<h3>Resources</h3>

https://vwo.com/push-notifications/
https://documentation.onesignal.com/docs