Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 25, 2021 01:08 am GMT

Push Notifications in ReactJS with OneSignal

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.

Topics covered in this tutorial

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

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

What is a Push Notification?

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.

Time to get our hands dirty!!!

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

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

The first thing that we have to do is to create an account inside of OneSignal

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

OneSignal React

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 NEXT.

OneSignal React

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

Notes

-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 this 2min tutorial.

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

OneSignal

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.

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 this article.

DO NOT CLOSE THE CONFIG PAGE. WE WILL BE BACK TO IT SOON.

Integrating OneSignal To Your ReactJS App

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.

Github repo

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 PUBLIC folder.

You should be adding 2 files:

  • OneSignalSDKUpdaterWorker.js
  • OneSignalSDKWorker.js

OneSignal React

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

<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
Enter fullscreen mode Exit fullscreen mode

Your file should look something like this:

<head>...  <title>One Signal - React</title>  <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script></head>
Enter fullscreen mode Exit fullscreen mode

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

  window.OneSignal = window.OneSignal || [];  const OneSignal = window.OneSignal;
Enter fullscreen mode Exit fullscreen mode

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 index.html file.

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

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);        })      );    });
Enter fullscreen mode Exit fullscreen mode

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 prompt message 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

categories: Property that takes an array of tags. The Category Slidedown 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

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:

OneSignal.sendTag("new_app_version", "new_app_version", tagsSent => {   console.log('new_app_version TAG SENT', tagsSent);})
Enter fullscreen mode Exit fullscreen mode

sendTags 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 appId 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

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.

YAY! we are done with the code part!

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

OneSignal

-Click on Allow on the OneSignal prompt

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

OneSignal

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

OneSignal React

The OneSignal Platform

12) Let's go back to the OneSignal website. We are going to create a new Segment 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

A modal as the following will appear

OneSignal

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

OneSignal React

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

YAY! you have officially created you first Segment.

Time to test our application!

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

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

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

OneSignal React

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

OneSignal React

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

OneSignal React

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

OneSignal

Conclusion

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.

Resources

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


Original Link: https://dev.to/devpato/push-notifications-in-reactjs-with-onesignal-5bon

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To