By searching the internet, I finally developed a hook that allows me to detect when the user is trying to navigate to another page of the app
I'm using React Router v6, which doesn't have an easy way to do this (history and prompt have been deprecated)
I built a code sandbox where you can see it all working (it also uses Mui), you'll see my refactored version which is more understandable and uses javascript
As you can see, it has a /hooks/navigationBlocker that uses UNSAFE_NavigationContext (which was developed by the same guys that developed React Router)
import * as React from 'react';
import { UNSAFE_NavigationContext } from 'react-router-dom';
export function NavigationBlocker(navigationBlockerHandler, canShowDialogPrompt) {
const navigator = React.useContext(UNSAFE_NavigationContext).navigator;
React.useEffect(() => {
if (!canShowDialogPrompt) return;
const unblock = navigator.block((tx) => {
const autoUnblockingTx = {
...tx,
retry() {
unblock();
tx.retry();
}
};
navigationBlockerHandler(autoUnblockingTx);
});
return unblock;
});
}
I don't understand this code much, I guess it is so because I never used anything previous to react-router-dom v6
Is there a way to do the same without the use of UNSAFE_NavigationContext, I don't know why it's unsafe as its name suggests
Rafael