How to create PWA using react

What is Progressive Web App (PWA)

Progressive Web Apps progressively enhance web apps to look and feel like native apps. Just like native apps, It has an icon on the home screen, abilities like accessing the camera and its location and synchronizing data into the background.

There are three main words that can summarise the PWA.

More reliable: PWA is a more reliable means they load fast and even work if you are offline.

Fast: It quickly responds to the user's action.

Engaging:  Feels like a native mobile app on a mobile device. It offers a push notification when an app is closed.


How to create PWA with React?

Step 1: Set up a simple react app.

npx create-react-app name-of-pwa-app --template cra-template-pwa

The following is a breakdown of the given command:

npx: It helps you to run npm packages.

create-react-app: This command allows you to create a react application.

name-of-pwa-app: This is the name of the app.

cra-template-pwa: CRA 4 or later does not provide built-in service workers, the argument —template cra-template-pwa is added to enable the creation of apps with service workers.

You can navigate to this directory with the following command:

cd name-of-pwa-app

The initial folder structure will look like this:

To run your app in the development mode, run the following command:

npm start

You can view your application on the browser by using the following -

  Local: http://localhost:3000

Step 2: Register a service worker

CRA gives you all the tools you need to deal with the problem of how to build a PWA using React. But how can you enable offline functionality for a React progressive web app? The automatically created service worker file needs to be registered and configured.
The file index.js is created in the project directory that you just generated. Open it, and you'll see the code below:


Service workers are not registered here. You have to change the unregister() to register().

Step 3: Update the manifest.json file.

Here, you need to change the metadata that defines how your application looks. Your manifest file will initially seem as follows:

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


To know more about manifest.json file attribute. Click here.

Step 4: Test your PWA
Now, we know how to make a React PWA. The next step is testing your app. When you want to run your app in production mode, use the following commands:

npm run build
serve -s build

Now you can go to the browser and install PWA.


Stay tuned for more blogs on PWA!!!

Dnyaneshwari Abuj

Dnyaneshwari Abuj

Beed.