If you want to block the user from navigating away from a page in a React app using React Router, you can use history.block and also display a dialog to ask if the user wants to navigate away from the page. Here’s how to do it:

We are going to use a callback function in order to block the user from navigating away from the page, display a dialog to ask them what they want to do, and unblock their navigation if they so choose.

const unblock = history.block((x) => {


    //Get the URL
    let url = x.location.pathname;

    //Display confirmation window to user
    if(window.confirm(`Are you sure that you want to leave ${url}?`)) {
        unblock();
    }

    //Attempt the transition once again
    x.retry();

})