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.

Discussion (4)

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 Author • 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 !