Skip to content

Instantly share code, notes, and snippets.

@coryhouse
Last active January 7, 2022 11:53
Show Gist options
  • Save coryhouse/811dcfc0e58f6c945611b297baee9d71 to your computer and use it in GitHub Desktop.
Save coryhouse/811dcfc0e58f6c945611b297baee9d71 to your computer and use it in GitHub Desktop.
Prompt user when they navigate away
import React, { useEffect } from "react";
import PropTypes from "prop-types";
import { Prompt } from "react-router-dom";
// Prompt the user onbeforeunload or when navigating away by clicking a link
export default function PromptOnUnload({ when, message }) {
const enabled = when;
useEffect(() => {
if (!enabled) return;
const handleBeforeUnload = (event) => {
event.preventDefault();
event.returnValue = ""; // Chrome requires setting this.
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, [enabled]);
return <Prompt when={enabled} message={message} />;
}
PromptOnUnload.propTypes = {
/** Set to true to enable the prompt */
when: PropTypes.bool.isRequired,
/** Message to display when the user navigates away by clicking a local link.
* This is also used as a requested message for onbeforeunload when the user refreshes the page or tries to close the tab.
* NOTE: Most browsers don't display a requested message when onbeforeunload fires, so the message
* is primarily useful to prompt the user when they're navigating away via a local React Router link. */
message: PropTypes.string,
};
PromptOnUnload.defaultProps = {
message: "Are you sure you want to leave?",
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment