Created
July 15, 2022 03:02
-
-
Save michchan/a7e0dd2de5ad6af05f90177759c4f239 to your computer and use it in GitHub Desktop.
RouteLeavingGuard full implementation 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 {Prompt} from 'react-router-dom' | |
import {CustomModal} from './CustomModal' | |
export class RouteLeavingGuard extends React.Component { | |
state = { | |
modalVisible: false, | |
lastLocation: null, | |
confirmedNavigation: false, | |
} | |
showModal = (location) => this.setState({ | |
modalVisible: true, | |
lastLocation: location, | |
}) | |
closeModal = (callback) => this.setState({ | |
modalVisible: false | |
}, callback) | |
handleBlockedNavigation = (nextLocation, action) => { | |
const {confirmedNavigation} = this.state | |
const {shouldBlockNavigation} = this.props | |
if (!confirmedNavigation && shouldBlockNavigation(nextLocation)){ | |
this.showModal(nextLocation) | |
return false | |
} | |
return true | |
} | |
handleConfirmNavigationClick = () => this.closeModal(() => { | |
const {navigate} = this.props | |
const {lastLocation} = this.state | |
if (lastLocation) { | |
this.setState({ | |
confirmedNavigation: true | |
}, () => { | |
// Navigate to the previous blocked location with your navigate function | |
navigate(lastLocation.pathname) | |
}) | |
} | |
}) | |
render() { | |
const {when} = this.props | |
const {modalVisible, lastLocation} = this.state | |
return ( | |
<> | |
<Prompt | |
when={when} | |
message={this.handleBlockedNavigation}/> | |
<CustomModal | |
visible={modalVisible} | |
onCancel={this.closeModal} | |
onConfirm={this.handleConfirmNavigationClick}/> | |
</> | |
) | |
} | |
} | |
export default RouteLeavingGuard |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment