Last active
April 11, 2024 12:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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