In this week of Hacktoberfest, I added push notifications to the Node Chat project in my most recent Pull request. I used the Push.js library in order to accomplish this task. Well learning how to do this, I din’t find much documentation on using Push.js with React so I put together a small tutorial for today’s blog.
Integrating Push.js with React
Natively, there is currently no solution to use Push.js with React. In order to use Push.js with react you have to use it as an external libraries. Below is how I added Push.js to React as an external library.
First step:
Include the script file in the main “index.html” file for your app.
I used a CDN to do this:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/push.js/1.0.7/push.min.js"></script>
Second step:
Import Push.js into your file.
Put the following line at the top of the .js file you want to use Push.js in.
import * as Push from "push.js";
After importing Push.js you can now create push notifications inside your react app.
Here’s an example of how to create a notification in a react component.
notify(){
Push.create("Hello world!", {
body: "Thanks for reading my Blog!",
timeout: 5000,
onClick: function () {
window.focus();
this.close();
}
});
}