react-router-prompt-plus
v2.0.3
Published
A React library to block route transitions and show confirm prompt.
Maintainers
Readme
react-router-prompt-plus
Block navigation in React Router and show a custom confirmation dialog before leaving the page.
✨ Features
- ✅ Blocks route transitions (
[email protected] - 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
📦 Installation
npm install react-router-prompt-plus✨ Example
✨ Demo react-router-dom version 6.4.0 - latest version 6
✨ Demo react-router-dom version 7
🚀 Usage
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>
)
}⚙️ API
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;
}🛠️ License
This project is licensed under the MIT License - see the LICENSE file for details.
