DEV Community

Santiago
Santiago

Posted on

Simplest React Hook component for PWA install button

This is the simplest snippet I could come up with to add a button which will prompt the user for the install pop up of your PWA.
It doesn't use any redux, nor nothing.

import React, { useEffect, useState } from "react"; const InstallPWA = () => { const [supportsPWA, setSupportsPWA] = useState(false); const [promptInstall, setPromptInstall] = useState(null); useEffect(() => { const handler = e => { e.preventDefault(); console.log("we are being triggered :D"); setSupportsPWA(true); setPromptInstall(e); }; window.addEventListener("beforeinstallprompt", handler); return () => window.removeEventListener("transitionend", handler); }, []); const onClick = evt => { evt.preventDefault(); if (!promptInstall) { return; } promptInstall.prompt(); }; if (!supportsPWA) { return null; } return ( <button className="link-button" id="setup_button" aria-label="Install app" title="Install app" onClick={onClick} > Install </button>  ); }; export default InstallPWA; 

Any feedback is welcome.

Top comments (9)

Collapse
 
dance2die profile image
Sung M. Kim

Thanks for the handy hook, Santiago.

One thing I want to mention is hooks should start with use, according to the official lint rules.
reactjs.org/docs/hooks-faq.html#wh...

So instead of InstallPWA, useInstallPWA.

Collapse
 
woile profile image
Santiago • Edited

It's a component, not a hook. This let's you add a install button if pwa is supported on the browser. It's built with hooks, but not intended to be used as a hook

Collapse
 
dance2die profile image
Sung M. Kim

Woops. you are right...

I am sorry about that 😅

Collapse
 
damjanevski profile image
Damjan

Finally something simple thanks Santiago !

Collapse
 
sonxauxa profile image
Son nguyen

You safe my day T_T, I got problem with beforeinstallprompt and querySelector from docs, and i dont know how

Collapse
 
rahulreddyv profile image
rahulreddyv

Can you help with a typescript one as well?

Collapse
 
jalbertsr profile image
Joan Albert Segura

why unsubscribe from the "transitionend" event? and what it does?

Collapse
 
woile profile image
Santiago

Hey I don't remember anymore, try removing and see the behaviour, I recall something was happening so I decided to stop it.

Collapse
 
yvan99 profile image
Ishimwe Yvan

is there a way we can render that button without refreshing the page . im calling the installPWA component in another page but in order to show up i have to refresh that page