AppDividend
Latest Code Tutorials

How To Build Progressive Web Application Using React js

3,618

Get real time updates directly on you device, subscribe now.

In this tutorial. We will see How To Build Progressive Web Application Using React js.  Progressive Web app uses the best of web and the best of apps to give a smooth experience to users and feels like the native app. We will see how compatible they are with existing architectures using libraries like React.js. Progressive web apps take advantages of latest web development tools and give users to mobile sites and native users experience. PWA is fast, reliable and needs to be run in secure mode. So HTTPS is required to run the Progressive web apps.

Progressive Web Application(PWA)

A Progressive Web App (PWA) is a web app that uses advanced web capabilities to provide an app-like experience to users. Unlike traditional applications, Progressive web apps are a hybrid of regular web pages (or websites) and a mobile application. This new application model attempts to combine features offered by most modern browsers with the benefits of mobile experience.” These apps meet specific requirements and are deployed to servers, accessible through URLs, and indexed by search engines. If you are building for the web, then I am pretty sure that PWA is the latest term that has been added to your work vocabulary. It is not surprising because PWA has made the far-fetched dream of installing web apps on the phone for real.

Build Progressive Web Application Using React js

In this project, we will see how we can setup the environment to build the React js Progressive web application. To Audit the progressive web application, we need to install the Google Chrome Plugin called Lighthouse. Lighthouse tells us the errors needs to be fixed to build the Progressive web application.

Step 1: Install the react js project.

In the terminal, type the following command.

npm install -g create-react-app
create-react-app pwa-react-app

After installing the project, start the application using the following command.

npm start

Our application is running on http://localhost:3000/

Okay, now we have installed the Lighthouse plugin to audit our PWA. So click the lighthouse icon in the upper right corner of the browser and generate the report for our URL: http://localhost:3000/ You can see our report looks something like this.

React js progressive web apps

 

It is the full audit report and as you can see in the screenshot that our website or web app is not fully compliant with the Progressive Web Application. PWA errors are the following for our application.

Lighthouse Tutorial

 

We need to fix those six failed audits to build an entirely progressive web application.

Step 2: Register a Service Worker.

Services worker act as proxy servers that sit between app and network. Using service worker, we will intercept the network requests and serve the cached files.  It will allow our web app to work even if a system is offline. However, React js is providing one registerWorker.js file inside src folder, but I am making another. First, create a blank service-worker.js file inside the public folder. Add the following code to it.

// service-worker.js

// Flag for enabling cache in production
var doCache = false;

var CACHE_NAME = 'pwa-app-cache';

// Delete old caches
self.addEventListener('activate', event => {
  const currentCachelist = [CACHE_NAME];
  event.waitUntil(
    caches.keys()
      .then(keyList =>
        Promise.all(keyList.map(key => {
          if (!currentCachelist.includes(key)) {
            return caches.delete(key);
          }
        }))
      )
  );
});

// This triggers when user starts the app
self.addEventListener('install', function(event) {
  if (doCache) {
    event.waitUntil(
      caches.open(CACHE_NAME)
        .then(function(cache) {
          fetch('asset-manifest.json')
            .then(response => {
              response.json();
            })
            .then(assets => {
              // We will cache initial page and the main.js
              // We could also cache assets like CSS and images
              const urlsToCache = [
                '/',
                assets['main.js']
              ];
              cache.addAll(urlsToCache);
            })
        })
    );
  }
});

// Here we intercept request and serve up the matching files
self.addEventListener('fetch', function(event) {
  if (doCache) {
    event.respondWith(
      caches.match(event.request).then(function(response) {
        return response || fetch(event.request);
      })
    );
  }
});

Now, add the following code inside index.html to check that whether the browser supports the service-worker.js file or not.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#f8f9fa"/>
    <link rel="manifest" href="./manifest.json"/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"/>
    <title>React App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root" class="container"></div>
    <script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('service-worker.js').then(function(registration) {
            console.log('Service Worker registration successful', registration.scope);
          }, function(err) {
            console.log('Service Worker registration failed', err);
          }).catch(function(err) {
            console.log(err);
          });
        });
      } else {
        console.log('Service Worker is not supported by browser.');
      }
    </script>

  </body>
</html>

After adding the code, see your browser’s console panel and if you find the message like “Service Worker registration successful http://localhost:3000/” then your browser is supporting the service-worker otherwise not supported.

Now, again go the lighthouse and again audit our web application.

PWA Tutorial with example from scratch

 

You can see that now there are only five errors and service workers error is resolved.

 Step 3: Tell the browser it’s a PWA.

Now, we need to add some code to tell the browser that this is not an ordinary web application, this is the progressive web application. So add the following code inside <head> tag in the index.html file.

<meta name="mobile-web-app-capable" content="yes">

Now, same for mobile device and especially iOS devices.

Related Posts
1 of 14
<meta name="apple-mobile-web-app-capable" content="yes">

Step 4: Create some bootstrap react components.

First, add the bootstrap to our project. For this tutorial, I am using CDN. So add the link inside the index.html file. Also, create one components folder inside src folder.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Now, create one component called Navbar.js inside components folder.

// Navbar.js

import React, { Component } from 'react';

export default class Navbar extends Component {
  render() {
    return (
      <nav className="navbar navbar-expand-lg navbar-light bg-light">
         <a className="navbar-brand" href="https://appdividend.com/">AppDividend</a>
         <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span className="navbar-toggler-icon"></span>
         </button>
         <div className="collapse navbar-collapse" id="navbarNav">
            <ul className="navbar-nav">
               <li className="nav-item">
               <a className="nav-link" href="https://appdividend.com/">Blog</a>
               </li>
            </ul>
         </div>
      </nav>
    );
  }
}

Now, add Navbar.js component inside App.js file.

// App.js

import React, { Component } from 'react';
import Navbar from './components/Navbar';

class App extends Component {
  render() {
    return (
      <div>
        <Navbar />
      </div>
    );
  }
}

export default App;

Now, create new component inside components folder called Content.js.

// Content.js

import React, { Component } from 'react';

export default class Content extends Component {
  render() {
    return (
      <div className="card">
         <div className="card-body">
         <h5 className="card-title">React PWA Example</h5>
         <p className="card-text">A Progressive Web App (PWA) is a web app that uses advanced web capabilities to provide an app-like experience to users. Unlike traditional applications, Progressive web apps are a hybrid of regular web pages (or websites) and a mobile application.</p>
         <a href="https://appdividend.com" className="btn btn-primary">Go somewhere</a>
         </div>
      </div>
    )
   }
}

Now, also add this component inside App.js file.

// App.js

import React, { Component } from 'react';
import Navbar from './components/Navbar';
import Content from './components/Content';

class App extends Component {
  render() {
    return (
      <div>
        <Navbar />
        <br/>
        <Content />
      </div>
    );
  }
}

export default App;

So we have created essential component powered by the progressive web application.

Step 5: Add Splash icons.

We need to add a 512×512 icon to show up on the splash screen. For doing so, we need to update the manifest.json and put the icon in public folder.

{
  "short_name": "React PWA App",
  "name": "Create React PWA Sample",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {  
      "src": "icon.png",
      "sizes": "512x512",  
      "type": "image/png"  
    }
  ],
  "start_url": "./index.html",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

Step 6: Deploy our application in the firebase.

We’re now only missing HTTPS and caching which will be fixed after deploy. Update the doCache flag to true in a service-worker.js file. Next, create a new project in firebase-console with name React Pwa App. Run the following commands in a project directory.

npm install -g firebase-tools
firebase login
firebase init

If you have not created the project in firebase, then please go to https://firebase.google.com/ and create a new project. After initialization of firebase, your firebase.json file looks like this.

{
  "database": {
    "rules": "database.rules.json"
  },
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "hosting": {
    "public": "build",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "storage": {
    "rules": "storage.rules"
  }
}

Make sure your hosting object looks like above file. If you have not configured the database then it is ok, our application does not need the database.

Finally, build the production version of the application.

npm run build

Now, deploy the application in the firebase.

firebase deploy

You can see this application live.

https://reactpwaapp.firebaseapp.com/

We can audit our progressive web application and now we get 100% compliance.

PWA using React js Tutorial

 

Open on the mobile phone and now you can able to the add the application on the home screen and after clicking that icon, you can see, we can run that application offline as well. I have put this application’s code on Github as well.

Finally, our Build Progressive Web Application Using React js is over. Thanks for taking.

Fork Me On Github

 

 

1 Comment
  1. SJohan says

    Nicely done! Thank you for your time!

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.