Last active
March 26, 2020 15:57
-
-
Save robertgonzales/e54699212da497740845712f3648d98c to your computer and use it in GitHub Desktop.
How to make a custom Prompt (using getUserConfirmation) for React Router v4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// use Prompt like normal... magic happens in getUserConfirmation | |
class App extends Component { | |
render () { | |
return ( | |
<Router getUserConfirmation={getUserConfirmation}> | |
{...} | |
<Prompt | |
when={formIsHalfFilledOut} | |
message="Are you sure you want to leave?" | |
/> | |
</Router> | |
) | |
} | |
} | |
ReactDOM.render( | |
<App />, | |
document.getElementById('root') | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// default behavior uses window.confirm | |
const getUserConfirmation = (message, callback) => { | |
const modal = document.createElement('div') | |
document.body.appendChild(modal) | |
const withCleanup = (answer) => { | |
ReactDOM.unmountComponentAtNode(modal) | |
document.body.removeChild(modal) | |
callback(answer) | |
} | |
ReactDOM.render( | |
<UserConfirmation | |
message={message} | |
onCancel={() => withCleanup(false)} | |
onConfirm={() => withCleanup(true)} | |
/>, | |
modal | |
) | |
} |
how this getUserConfirmation work? Will it not let the user redirect to any other URL, if callback(false) is returned?
@thekoolfunda
getUserConfirmation prevent of changing URL address, but at the moment of showing confirm dialog the URL adress has already changed to the next URL and after callback(false) the URL returns to the privious state.
A lot of colleagues asked me to tell them how it works and i created a demo and short video with explanations, may be it will be usefull for someone too:
EN: https://youtu.be/ZE5I9RbMaGY
RU: https://youtu.be/qDJ2OMcz8is
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can you change the value of
formIsHalfFilledOut
after confirmation, so that that theUserConfirmation
isn't opened again immediately?It can be done by dispatching a Redux action from the
withCleanup
, but I don't use Redux. A top level React context Provider seems unable to pass any value to theUserConfirmation
, probably since the node is rendered separately, so that doesn't work either.Is it possible to pass a custom callback to
getUserConfirmation
in order to reset thePrompt
?