react-router-prompt-plus
TypeScript icon, indicating that this package has built-in type declarations

2.0.3 • Public • Published

react-router-prompt-plus

Block navigation in React Router and show a custom confirmation dialog before leaving the page.

✨ Features

  • ✅ 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

📦 Installation

npm install react-router-prompt-plus

🚀 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.

Package Sidebar

Install

npm i react-router-prompt-plus

Weekly Downloads

16

Version

2.0.3

License

MIT

Unpacked Size

8.26 kB

Total Files

7

Last publish

Collaborators

  • tuanndl