Put A Warning If Page Refresh in ReactJS

If you want to display a sort of confirmation before leaving the page then follow the beforeunload event guidelines

According to the specification, to show the confirmation dialog an
event handler should call preventDefault() on the event.

However note that not all browsers support this method, and some
instead require the event handler to implement one of two legacy
methods:

  • assigning a string to the event’s returnValue property
  • returning a string from the event handler.

To combat unwanted pop-ups, browsers may not display prompts created
in beforeunload event handlers unless the page has been interacted
with, or may even not display them at all.

The HTML specification states that calls to window.alert(),
window.confirm(), and window.prompt() methods may be ignored during
this event. See the HTML specification for more details.

I just tested this in chrome and safari and it works. I don’t have a windows box, but this should cover most cases.

useEffect(() => {
  const unloadCallback = (event) => {
    event.preventDefault();
    event.returnValue = "";
    return "";
  };

  window.addEventListener("beforeunload", unloadCallback);
  return () => window.removeEventListener("beforeunload", unloadCallback);
}, []);

enter image description here
enter image description here

Edit put-a-warning-if-page-refresh-in-reactjs

Leave a Comment