React-router: Support function for Prompt when prop

Created on 14 Mar 2017  路  6Comments  路  Source: ReactTraining/react-router

Now the Prompt component only support a boolean that enable or not the navigation. This means that we need to know at at render time that navigation is allowed or not. Sometimes we want to check a condition just at navigation time and in this case we should be able to pass a function instead of a boolean (history lib already support a function in the block function so it should be trivial to implement this feature).
I would like to be able to write something like that:

<Prompt when={(location, action) => {
  // The location and action arguments indicate the location
  // we're transitioning to and how we're getting there.

  // A common use case is to prevent the user from leaving the
  // page if there's a form they haven't submitted yet.
  if (input.value !== '')
    return 'Are you sure you want to leave this page?'
}}

and when we use a function for the when prop then we do not provide the message prop as the function already return the message to display.

feature

Most helpful comment

This is definitely possible using the above code, but seems like a hacky workaround. Would y'all be open to a PR that allows a function for the when parameter?

All 6 comments

Seems like a good idea. This would be best as a PR and should be pretty simple. If someone wants to put one together (with tests!), that would be awesome.

Ah, so this would be handy when you are rendering a prompt in a deep view pretty far away from a route component?

As far as I can tell, this should already be possible by passing a function to message and setting when to true (which is the default, so it can be omitted).

<Prompt message={(location, action) => {
  // The location and action arguments indicate the location
  // we're transitioning to and how we're getting there.

  // A common use case is to prevent the user from leaving the
  // page if there's a form they haven't submitted yet.
  if (input.value !== '')
    return 'Are you sure you want to leave this page?'
}} />

docs

Good call, thanks.

:+1:

This is definitely possible using the above code, but seems like a hacky workaround. Would y'all be open to a PR that allows a function for the when parameter?

Was this page helpful?
0 / 5 - 0 ratings