A React library to block route transitions and show confirm prompt.
npm install react-router-prompt-plusBlock 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
---
``bash`
npm install react-router-prompt-plus
`typescript
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 (
Are you sure you want to leave this page?
⚙️ API
usePrompt(options: UsePromptOptions): UsePromptReturnOptions
| 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
`typescript
{
showPrompt: boolean;
handleConfirm: () => void;
handleCancel: () => void;
}
``This project is licensed under the MIT License - see the LICENSE file for details.