Daily Coding Tips №71 — how to do confirm navigation or prevent transitions via react-router?

1. react-router version 4

If you are using react-router version 4, you can simply use the new Prompt component it provides:

import { BrowserRouter as Router, Route, Link, Prompt } from "react-router-dom";
<Prompt
when={isBlocking}
message={location => `Are you sure you want to go to ${location.pathname}`}
/>

2. react-router version 3

If you are using react-router version 3, you can use the leave hook:

componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave)
}