Skip to content

Instantly share code, notes, and snippets.

@shikelong
Created December 3, 2021 03:57
Show Gist options
  • Save shikelong/822da08946ab802360004ba81bf81b81 to your computer and use it in GitHub Desktop.
Save shikelong/822da08946ab802360004ba81bf81b81 to your computer and use it in GitHub Desktop.
react-router Block Route Change
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