1

I'm using React-Router's Prompt component to block a user from switching tabs when a form is in a dirty state. Each tab has its own route and I'm using history.push to update the URL. Prompt shows up as expected when the form is dirty, but the user is still taken to the new URL when they click "cancel".

Here is the function that handles switching tabs and updating the URL.

const handleClick = (tabId, disabled, route) => {
    if (disabled) {
        return false;
    }
    setSelectedIndex(tabId);
    if (route) {
        history.push(route);
    }
    return true;
};

I'm guessing that history.push gets executed not matter what.

Every example I see of using Prompt shows it being used with Link. Is there a way to get Prompt to work with history.push?

Michael Turnwall
  • 649
  • 7
  • 21
  • The answer in this question looks like it does what you want. https://stackoverflow.com/questions/1119289/how-to-show-the-are-you-sure-you-want-to-navigate-away-from-this-page-when-ch – azium Feb 25 '20 at 18:05
  • I've seen that one before. Unfortunately pushing to the history stack does not fire the browser's unload event. – Michael Turnwall Feb 25 '20 at 18:22
  • this is the code for prompt https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Prompt.js#L19 maybe history.block might work? haven't tried it myself – azium Feb 25 '20 at 18:26
  • My understanding is that `history.block` is going away https://github.com/ReactTraining/history/issues/690 – Michael Turnwall Feb 25 '20 at 18:48
  • 1
    @MichaelTurnwall I am trying to accomplish the same thing, did you ever solve this? – David Allen May 18 '20 at 21:48
  • Yes, you can use https://michaelchan-13570.medium.com/using-react-router-v4-prompt-with-custom-modal-component-ca839f5faf39 . It blocks history.push and history.replace (I'd add it as an answer, but since I'm not the original author of the solution, I preferred to let it here) – João Bruno Abou Hatem de Liz Jan 20 '21 at 16:24

0 Answers0