Search code examples
javascriptreactjsreact-routerreact-router-dom

Detecting user leaving page with react-router-dom v6.0.2


I am trying to show Dialog Box for unsaved changes before navigating to other route or page in ReactJS web app. I tried different solution from Stackoverflow but didn't succeeded. Most of solution related to older version. I need for version 6.0.2 (react-router-dom). Anyone who can help me out in this really appreciated.


Solution

  • How to resolve my problem? Instead of downgrading, I created two custom hooks.

    1. useCallbackPrompt Hook
    2. useBlocker Hook

    useCallbackPrompt Hook This hook handles a popup to show & hide and update location on the base of specific conditions. How it looks like. useCallbackPrompt Hook

    useBlocker Hook This hooks blocks users from navigating away if there are any changes useBlocker Hook

    How I am using useCallbackPrompt in my component component where I am using useCallbackPrompt hook

    I created state showDialog; If the user changes something on the current page/form it will update the state showDialog and If the user tries to navigate away the prompt will be shown, and ask if the user wants to stay or not.

    Here is the Live Demo Link

    Here is the GITHUB REPO LINK

    Link for Post