Block navigation in React Router and show a custom confirmation dialog before leaving the page.
- ✅ Blocks route transitions (
react-router-dom@6.4.0 - latest
) and shall be ideally used with data routers - ✅ Supports
beforeunload
(tab close, reload) - ✅ UI agnostic – you write your own confirmation UI
- ✅ Built with TypeScript
npm install react-router-prompt-plus
import { usePrompt } from "react-router-prompt-plus"
function MyForm() {
const [isDirty, setIsDirty] = useState(false)
const { showPrompt, handleConfirm, handleCancel } = usePrompt({
when: isDirty,
ignoreHash: true,
ignoreSearch: true,
})
const onConfirm = () => {
handleConfirm()
setIsDirty(false)
}
const onCancel = () => {
handleCancel()
}
return (
<div>
<input onChange={() => setIsDirty(true)} />
{showPrompt && (
<div className="modal">
<p>Are you sure you want to leave this page?</p>
<button onClick={onConfirm}>Yes</button>
<button onClick={onCancel}>No</button>
</div>
)}
</div>
)
}
usePrompt(options: UsePromptOptions): UsePromptReturn
Options
Name | Type | Default | Description |
---|---|---|---|
when | boolean | Whether to block navigation | |
beforeUnload | boolean | true | Block browser tab close/reload |
ignoreHash | boolean | false | Ignore comparing the hash field of currentLocation and nextLocation. |
ignoreSearch | boolean | false | Ignore comparing the search field of currentLocation and nextLocation. |
- Returns
{
showPrompt: boolean;
handleConfirm: () => void;
handleCancel: () => void;
}
This project is licensed under the MIT License - see the LICENSE file for details.