Created
July 15, 2022 03:07
-
-
Save michchan/22ace11c84e82707142040e6a7af25dc to your computer and use it in GitHub Desktop.
RouteLeavingGuard Usage for Medium article ca839f5faf39
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
import React from ‘react’ | |
import RouteLeavingGuard from 'components/RouteLeavingGuard' | |
export class LoginScene extends React.Component { | |
state = { | |
username: '', | |
password: '', | |
isDirty: false, | |
} | |
// ...Other scene helper functions | |
render() { | |
const { isDirty } = this.state | |
const { history } = this.props | |
return ( | |
<React.Fragment> | |
// ...Other scene components | |
<RouteLeavingGuard | |
// When should shouldBlockNavigation be invoked, | |
// simply passing a boolean | |
// (same as "when" prop of Prompt of React-Router) | |
when={isDirty} | |
// Navigate function | |
navigate={path => history.push(path)} | |
// Use as "message" prop of Prompt of React-Router | |
shouldBlockNavigation={location => { | |
// This case it blocks the navigation when: | |
// 1. the login form is dirty, and | |
// 2. the user is going to 'sign-up' scene. | |
// (Just an example, in real case you might | |
// need to block all location regarding this case) | |
if (isDirty) { | |
if (location.pathname === 'signup') { | |
return true | |
} | |
} | |
return false | |
}} | |
/> | |
</React.Fragment> | |
) | |
} | |
} | |
export default LoginScene |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment