Created
May 6, 2020 18:54
-
-
Save MeyCry/a879dec08da3ad3563155b9787293e0a to your computer and use it in GitHub Desktop.
reject react router v5 navigate
This file contains hidden or 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 { Location } from "history"; | |
import React, { useEffect, useState } from "react"; | |
import { Prompt } from "react-router-dom"; | |
import { SubmitDialogComponent } from "./Modal"; | |
interface Props { | |
when?: boolean | undefined; // just use true | |
navigate: (path: string) => void; // (path) => history.push(path) | |
shouldBlockNavigation: (location: Location) => boolean; | |
} | |
export const RouteLeavingGuard = ({ | |
when, | |
navigate, | |
shouldBlockNavigation, | |
}: Props) => { | |
const [modalVisible, setModalVisible] = useState(false); | |
const [lastLocation, setLastLocation] = useState<Location | null>(null); | |
const [confirmedNavigation, setConfirmedNavigation] = useState(false); | |
const closeModal = () => { | |
setModalVisible(false); | |
}; | |
const handleBlockedNavigation = (nextLocation: Location): boolean => { | |
if (!confirmedNavigation && shouldBlockNavigation(nextLocation)) { | |
setModalVisible(true); | |
setLastLocation(nextLocation); | |
return false; | |
} | |
return true; | |
}; | |
const handleConfirmNavigationClick = () => { | |
setModalVisible(false); | |
setConfirmedNavigation(true); | |
}; | |
useEffect(() => { | |
if (confirmedNavigation && lastLocation) { | |
// Navigate to the previous blocked location with your navigate function | |
navigate(lastLocation.pathname); | |
} | |
}, [confirmedNavigation, lastLocation]); | |
return ( | |
<> | |
<Prompt when={when} message={handleBlockedNavigation} /> | |
{/* Your own alert/dialog/modal component */} | |
<SubmitDialogComponent | |
onSubmit={handleConfirmNavigationClick} | |
onClose={closeModal} | |
modalOpen={modalVisible} | |
headerText="Unsaved changes" | |
text="Are you sure you want to leave this page? Your changes will be lost forever..." | |
/> | |
</> | |
); | |
}; | |
// <WarningDialog | |
// open={modalVisible} | |
// titleText="Close without saving?" | |
// contentText="You have unsaved changes. Are you sure you want to leave this page without saving?" | |
// cancelButtonText="DISMISS" | |
// confirmButtonText="CONFIRM" | |
// onCancel={closeModal} | |
// onConfirm={handleConfirmNavigationClick} | |
// /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment