![]() |
Progressive Web Apps (PWAs) have emerged as a game-changer, offering a blend of website accessibility and native mobile app capabilities, thereby presenting the best of both worlds. Table of Content
What is a Progressive Web App (PWA)?Progressive Web Apps (PWAs) are web applications that offer a native app-like experience on the web. They are reliable, fast, and engaging, offering features such as offline access, push notifications, and home screen installation. In this article, we’ll explore how to make a React application a PWA. Key Features of PWA
Steps to Transform Your React App into a PWAWe will Create a simple React-based web application that fetches a list of popular movies from The Movie Database (TMDb) API and displays them in a user-friendly format. The app demonstrates basic concepts in React, including state management, component rendering, and API integration. npx create-react-app pwa-application
cd pwa-application Get TMDb API KeyFollow these steps to get an API key from TMDb:
Enable HTTPSSecurity is crucial for PWAs. Configure your web server to serve your app over HTTPs. Let’s assume you have a mechanism in place (like a free SSL certificate from Let’s Encrypt) to handle this. Add a Web App Manifest (WAM): (manifest.json)The WAM is a JSON file that provides essential information about your PWA, including its name, icons, theme color, and startup screen. Create a file named manifest.json at the root of your project directory and add the following content, customizing it for your app: This JSON file provides metadata about your PWA, including its name, icons, and installation behavior on the home screen public->manifest.json manifest.json
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "maskable_icon_x192.png",
"type": "image/png",
"sizes": "192x192",
"purpose":"any maskable"
},
{
"src": "maskable_icon_x192.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
Register a Service Worker:(optional, but recommended for core PWA features)A service worker is a script that runs in the background, enabling functionalities like offline access, push notifications, and background sync. Create a file named serviceWorker.js in your public directory and add the following code: public->index.html <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script>
if('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('./serviceWorker.js').then((reg) => {
console.log('Worker Registered')
}).catch((err) => {
console.log('Error in service worker registration.')
})
})
}
</script>
</body>
</html>
Implementing Offline FunctionalityService Worker Caching: Utilize the Service Worker Caching API to cache static assets like HTML, CSS, JavaScript, and images. Now inside the public create serviceWorker.js //STORAGE OF BROWSER
const CACHE_NAME = "version-1";
const urlsToCache = ["index.html", "offline.html"];
const self = this;
//installation
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log("Opened cache");
return cache.addAll(urlsToCache);
})
);
});
// listen for request
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((res) => {
return fetch(event.request).catch(() => caches.match("offline.html"));
})
);
});
// actitivate the service worker
self.addEventListener("activate", (event) => {
const cacheWhitelist = [];
cacheWhitelist.push(CACHE_NAME);
event.waitUntil(
caches.keys().then((cacheNames) => Promise.all(
cacheNames.map((cacheName) => {
if(!cacheWhitelist.includes(cacheName)){
return caches.delete(cacheName);
}
})
))
)
});
Register the Service Worker (index.js)In your src/index.js file, import and register the service worker:
Enabling Push Notifications (Optional)Push notifications are a powerful way to re-engage users and keep them informed even when they’re not actively using your app. By implementing push notifications in your React PWA with Firebase Cloud Messaging (FCM), you can:
Steps to Create a React AppStep 1: Create a React application using the following command: npx create-react-app pwa-application Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd pwa-application Step 3: Install the required dependencies in your project using the following command: npm install axios Project Structure:![]() Project Structure: The updated dependencies in your packge.json file is: "dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"axios": "^1.6.7",
},
Start your application using the following command: npm start Output: ![]() Final output ConclusionBy following these steps, you’ve converted the “Movie List Application” into a Progressive Web App. This PWA has a service worker for offline support, a manifest file for metadata and icons, and HTTPS for security. It’s installable on users’ devices and works even when offline, providing a more engaging user experience. |
Reffered: https://www.geeksforgeeks.org
ReactJS |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |