reactjsreact-router

How to prevent route change using react-router


There's a certain page in my React app that I would like to prevent the user from leaving if the form is dirty.

In my react-routes, I am using the onLeave prop like this:

<Route path="dependent" component={DependentDetails} onLeave={checkForm}/>

And my onLeave is:

const checkForm = (nextState, replace, cb) => {
  if (form.IsDirty) {
    console.log('Leaving so soon?');
    // I would like to stay on the same page somehow...
  }
};

Is there a way to prevent the new route from firing and keep the user on the same page?


Solution

  • It is too late but according to the React Router Documentation you can use preventing transition with helping of <prompt> component.

      <Prompt
          when={isBlocking}
          message={location =>
            `Are you sure you want to go to ${location.pathname}`
          }
        />
    

    if isBlocking equal to true it shows a message. for more information you can read the documentation.