I have a Progressive Web App that uses react-router with the history package for navigation. On a certain route, i want to display a button that allows the user to directly install the product to their device. The display of the button listens to the beforeinstallprompt
event. It stores the event in state and fires the event when the user presses the button, fairly straightforward code, as seen here:
import React from 'react';
import styled from 'styled-components';
import Button from 'components/common/button';
function InstallRoute() {
const [deferredPrompt, setDeferredPrompt] = React.useState(null);
const beforeInstallPrompt = (event) => {
event.preventDefault();
setDeferredPrompt(event);
};
React.useEffect(() => {
window.addEventListener('beforeinstallprompt', beforeInstallPrompt, true);
return () => {
window.removeEventListener('beforeinstallprompt', beforeInstallPrompt, true);
};
});
function install() {
if (!deferredPrompt) return;
deferredPrompt.prompt();
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
// accepted
} else {
// dismissed
}
setDeferredPrompt(null);
});
}
return (
<InstallWrapper visible={deferredPrompt !== null}>
<Button onClick={install}>Install app</Button>
</InstallWrapper>
);
}
const InstallWrapper = styled.div`
padding: 32px;
display: ${props => props.visible ? 'block' : 'none'};
`;
export default InstallRoute;
The problem however, is that the beforeinstallprompt
event only fires on initial load. Which means it only fires when you either refresh, or when navigating to that route using window.location = '/installroute'
. When navigating to the install route using history.push
or NavLink
from the react-router package, the event will not fire.
The install button works as intended when refreshing or a hard location change, but naturally, i want it to work with react-router/history as well. I don't want to pollute the project with dirty location changes.
Is there any solution to this? Is there maybe a different type of route element i should use for the install route, or an alternative to history.push
?