3

In older versions I could use setRouteLeaveHook within my component.

For example (SO): Detecting user leaving page

With react router v4 the logic has changed away from injecting the router itself into the components and I only found the following function on router v4:

BrowserRouter. getUserConfirmation

I am a little bit confused, why I should link the confirm behavior with the Router itself and not with a specific component!?

How can I place a confirm window, when leaving my component (linked to my current route), while being in a certain state? This seems to be not supported by the function above.

Jankapunkt
  • 8,128
  • 4
  • 30
  • 59

2 Answers2

16

I think the Prompt component is what you're looking for. Just render it in the component you want to confirm navigation form, i.e. the same component you render in your <Route>.

skept
  • 175
  • 1
  • 5
  • Looks promising and I wonder why I did not found it on react training before. Will check that out and respond on success/fail. – Jankapunkt Jun 22 '17 at 22:39
  • I've been looking for a way to have a custom prompt for the user, may be something like [ample-alerts](https://github.com/myTerminal/ample-alerts). However, most implementations use this specific method and it relies on the browser default prompt. – myTerminal Mar 22 '19 at 03:27
3

react-router-navigation-prompt also does what you want: it is a more powerful <Prompt />.

Zachary Ryan Smith
  • 2,688
  • 1
  • 20
  • 30