DEV Community

Cover image for Creating a Progressive Web App in React A Beginners Guide
Varshith V Hegde
Varshith V Hegde

Posted on

Creating a Progressive Web App in React A Beginners Guide

What is PWA?

Progressive Web App (PWA) is a web application that provides an experience similar to that of a native mobile app. PWAs are built using modern web technologies such as service workers, web app manifests, and push notifications, which allows them to work offline or on poor network connections, installable on a user's home screen, and provide an app-like experience.

One of the key benefits of PWAs is their ability to improve user engagement and satisfaction by providing an app-like experience in the browser. PWAs can also reduce development costs and make it easier to reach a wider audience since they work on a variety of devices and platforms.

How to Create a PWA in Simple Steps in React

If you're interested in creating a PWA in React, here are some simple steps to get started:

Step 1: Set up a React project

The first step is to set up a new React project using a tool such as Create React App. This will provide you with a basic React app that you can use as a starting point for your PWA.

Step 2: Install the necessary dependencies

Next, you'll need to install the necessary dependencies for creating a PWA in React. This includes the "workbox-webpack-plugin" and "web-push" packages.

npm install workbox-webpack-plugin web-push
Enter fullscreen mode Exit fullscreen mode
yarn add workbox-webpack-plugin web-push
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a service worker

A service worker is a JavaScript file that runs in the background and handles tasks such as caching resources and handling push notifications. To create a service worker in React, you can use the "workbox-webpack-plugin" package.

In your webpack configuration file, add the following code:


const WorkboxPlugin = require('workbox-webpack-plugin');

module.exports = {
  // ...
  plugins: [
    new WorkboxPlugin.GenerateSW({
      clientsClaim: true,
      skipWaiting: true,
    }),
  ],
};
Enter fullscreen mode Exit fullscreen mode

This will create a service worker that caches your app's resources and enables offline functionality.

Step 4: Create a web app manifest

A web app manifest is a JSON file that provides information about your app, such as its name, icon, and theme color. To create a web app manifest in React, you can add a manifest.json file to your public folder and fill it with the necessary information.

Here's an example manifest.json file:

{
  "name": "My PWA",
  "short_name": "My PWA",
  "icons": [
    {
      "src": "icon.png",
      "sizes": "192x192",
      "type": "image/png"
    }
  ],
  "theme_color": "#ffffff",
  "background_color": "#ffffff",
  "start_url": ".",
  "display": "standalone",
  "scope": "/"
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Enable push notifications

To enable push notifications in your PWA, you'll need to set up a push notification service such as Firebase Cloud Messaging (FCM). Once you've set up FCM, you can use the "web-push" package to handle push notifications in your app.

Here's an example code for handling push notifications:

const publicKey = 'your-public-key';

navigator.serviceWorker.register('/sw.js').then((registration) => {
  registration.pushManager
    .subscribe({
      userVisibleOnly: true,
      applicationServerKey: urlBase64ToUint8Array(publicKey),
    })
    .then((subscription) => {
      console.log('Subscription successful:', subscription);
      console.log(JSON.stringify(subscription));
    })
    .catch((error) => {
    console.log('Subscription failed:', error);
    });
  });

function urlBase64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
  const base64 = (base64String + padding)
  .replace(/-/g, '+')
  .replace(/_/g, '/');
  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }

  return outputArray;
}
Enter fullscreen mode Exit fullscreen mode

This code registers a service worker and subscribes to push notifications using the "web-push" package. It also converts the public key from a base64 string to a Uint8Array.

Step 6: Test your PWA

Once you've completed all of the above steps, you can test your PWA by running it in a browser or on a mobile device. You should be able to see your app's icon on your home screen, and it should work offline and support push notifications.

Desktop PWA

Conclusion

In this article, we've learned what a PWA is and how to create one in React. We've also learned how to set up a React project, install the necessary dependencies, create a service worker, create a web app manifest, and enable push notifications.

Top comments (0)