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)
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
.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
Woops. you are right...
I am sorry about that 😅
Finally something simple thanks Santiago !
You safe my day T_T, I got problem with beforeinstallprompt and querySelector from docs, and i dont know how
Can you help with a typescript one as well?
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
why unsubscribe from the "transitionend" event? and what it does?
Hey I don't remember anymore, try removing and see the behaviour, I recall something was happening so I decided to stop it.