Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created December 5, 2021 13:01
Show Gist options
  • Save ali-master/4f8e98184cfa0b875ff38bb15b668522 to your computer and use it in GitHub Desktop.
Save ali-master/4f8e98184cfa0b875ff38bb15b668522 to your computer and use it in GitHub Desktop.
Install a PWA application manually in React.js
import React, { useEffect, useRef } from 'react'
export const PWAInstallButton = () => {
const deferredPrompt = useRef(null)
useEffect(() => {
const handlePrompt = (e) => {
// Prevent the mini-infobar from appearing on mobile
e.preventDefault()
// Stash the event so it can be triggered later.
deferredPrompt.current = e
}
window.addEventListener('beforeinstallprompt', handlePrompt)
return () => window.removeEventListener('beforeinstallprompt', handlePrompt)
})
const installPWA = () => {
if (!deferredPrompt.current) return
deferredPrompt.current.prompt()
// Wait for the user to respond to the prompt
deferredPrompt.current.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
localStorage.setItem("pwa-is-installed", 'true')
}
})
}
return (
<button
type="button"
onClick={installPWA}
>
Install
</button>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment