Skip to content

Instantly share code, notes, and snippets.

@librz
Last active April 11, 2024 12:43
Show Gist options
  • Save librz/2487e9f3935806b25f66eda409637778 to your computer and use it in GitHub Desktop.
Save librz/2487e9f3935806b25f66eda409637778 to your computer and use it in GitHub Desktop.
React Router V6, Demo of prompt user for confirm when user navigate away or reload/close the page
import { useState } from "react";
import { useBeforeUnload, useBlocker } from "react-router-dom";
// unstable_usePrompt: https://reactrouter.com/en/main/hooks/use-prompt
// useBlocker: https://reactrouter.com/en/main/hooks/use-blocker
// useBeforeUnload: https://reactrouter.com/en/main/hooks/use-before-unload
export default function Form() {
const [input, setInput] = useState("");
// unstable_usePrompt({
// message: "Are you sure to leave this page?",
// when: ({ currentLocation, nextLocation }) => input && currentLocation.pathname !== nextLocation.pathname,
// });
useBlocker(({ currentLocation, nextLocation }) => {
if (input && currentLocation.pathname !== nextLocation.pathname) {
const confirmLeave = window.confirm("Are you sure to leave this page?");
return !confirmLeave;
}
return false; // do not block
});
useBeforeUnload((e) => {
if (input) {
e.preventDefault();
}
});
return (
<div>
<div style={{ marginBottom: 12 }}>Try navigate away or reload/close the page when input has value</div>
<input
type="text"
value={input}
onChange={(e) => {
setInput(e.target.value);
}}
style={{ padding: "4px 8px", fontSize: 16, borderRadius: 4 }}
/>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment