Created
December 3, 2021 03:57
-
-
Save shikelong/822da08946ab802360004ba81bf81b81 to your computer and use it in GitHub Desktop.
react-router Block Route Change
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 { useEffect } from "react"; | |
import { useHistory } from "react-router-dom"; | |
export const defaultLevelMessage = | |
"未保存のデータがあります。ページを離れてもよろしいですか。"; | |
function useBlockRouteChange( | |
shouldBlock: boolean, | |
message = defaultLevelMessage, | |
onLevel?: () => void | |
) { | |
const history = useHistory(); | |
useEffect(() => { | |
if (!shouldBlock) { | |
return; | |
} | |
/** | |
* FIXME: in React-Router v6, should confirm this method can be used. | |
* https://github.com/remix-run/history/issues/690 | |
*/ | |
let unblock = history.block(() => { | |
const shouldLevel = window.confirm(message); | |
if (shouldLevel && typeof onLevel === "function") { | |
onLevel(); | |
} | |
return shouldLevel; | |
}); | |
return () => { | |
unblock(); | |
}; | |
}, [shouldBlock, history, message, onLevel]); | |
} | |
export default useBlockRouteChange; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment