In a React project, I've created a popup modal which will be displayed when any user tries to do any changes in input field and navigate to other screen. It doesn't work as expected, hence gone through many posts to find the solution but, no luck. Please refer to code below:
useBlock.js
import {useContext, useEffect} from 'react';
import { UNSAFE_NavigationContext as NavigationContext} from 'react-router-dom';
const useBlocker = (blocker, when = true) => {
const navigator = useContext(NavigationContext).navigator
useEffect(() => {
if (!when)
return;
const unblock = navigator.block((tx) => { <-- This line is creating an issue
const autoUnblockingTx = {
...tx,
retry() {
unblock();
tx.retry();
},
};
blocker(autoUnblockingTx);
});
return unblock;
}, [navigator, blocker, when]);
}
export default useBlocker
useCallbackPrompt.js
import { useCallback, useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router';
import useBlocker from './useBlocker';
const useCallbackPrompt = (when) => {
const navigate = useNavigate();
const location = useLocation();
const [showPrompt, setShowPrompt] = useState(false);
const [lastLocation, setLastLocation] = useState(null);
const [confirmedNavigation, setConfirmedNavigation] = useState(false);
const cancelNavigation = useCallback(() => {
setShowPrompt(false);
}, []);
const handleBlockedNavigation = useCallback((nextLocation) => {
if (!confirmedNavigation &&
nextLocation.location.pathname !== location.pathname) {
setShowPrompt(true);
setLastLocation(nextLocation);
return false;
}
return true;
}, [confirmedNavigation]);
const confirmNavigation = useCallback(() => {
setShowPrompt(false);
setConfirmedNavigation(true);
}, []);
useEffect(() => {
if (confirmedNavigation && lastLocation) {
navigate(lastLocation.location.pathname);
}
}, [confirmedNavigation, lastLocation]);
useBlocker(handleBlockedNavigation, when);
return [showPrompt, confirmNavigation, cancelNavigation];
}
export default useCallbackPrompt
So above are the 2 files which I'm using. In useBlocker.js file that particular line is actually causing the root issue. Please refer to the image below
I'm using "react-router-dom": "^6.3.0"
, Is this causing any issue? Any suggestions or modifications are highly appreciated.
In a React project, I've created a popup modal which will be displayed when any user tries to do any changes in input field and navigate to other screen. It doesn't work as expected, hence gone through many posts to find the solution but, no luck. Please refer to code below:
useBlock.js
import {useContext, useEffect} from 'react';
import { UNSAFE_NavigationContext as NavigationContext} from 'react-router-dom';
const useBlocker = (blocker, when = true) => {
const navigator = useContext(NavigationContext).navigator
useEffect(() => {
if (!when)
return;
const unblock = navigator.block((tx) => { <-- This line is creating an issue
const autoUnblockingTx = {
...tx,
retry() {
unblock();
tx.retry();
},
};
blocker(autoUnblockingTx);
});
return unblock;
}, [navigator, blocker, when]);
}
export default useBlocker
useCallbackPrompt.js
import { useCallback, useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router';
import useBlocker from './useBlocker';
const useCallbackPrompt = (when) => {
const navigate = useNavigate();
const location = useLocation();
const [showPrompt, setShowPrompt] = useState(false);
const [lastLocation, setLastLocation] = useState(null);
const [confirmedNavigation, setConfirmedNavigation] = useState(false);
const cancelNavigation = useCallback(() => {
setShowPrompt(false);
}, []);
const handleBlockedNavigation = useCallback((nextLocation) => {
if (!confirmedNavigation &&
nextLocation.location.pathname !== location.pathname) {
setShowPrompt(true);
setLastLocation(nextLocation);
return false;
}
return true;
}, [confirmedNavigation]);
const confirmNavigation = useCallback(() => {
setShowPrompt(false);
setConfirmedNavigation(true);
}, []);
useEffect(() => {
if (confirmedNavigation && lastLocation) {
navigate(lastLocation.location.pathname);
}
}, [confirmedNavigation, lastLocation]);
useBlocker(handleBlockedNavigation, when);
return [showPrompt, confirmNavigation, cancelNavigation];
}
export default useCallbackPrompt
So above are the 2 files which I'm using. In useBlocker.js file that particular line is actually causing the root issue. Please refer to the image below
I'm using "react-router-dom": "^6.3.0"
, Is this causing any issue? Any suggestions or modifications are highly appreciated.
3 Answers
Reset to default 7I wasn't able to reproduce the issue using [email protected]
, but I could when bumping to [email protected]
. I suspect with a dependency specified as ^6.3.0
you've actually a more current version actually installed. If you like you can check the installed version by running npm list react-router-dom
and verify for yourself.
It seems the navigation context has a mildly breaking change between v6.3.0 and v6.4.0. The v6.3.0 version is a history object (source) while the v6.4.0 is a new navigation context object where navigator
is a simpler interface (source).
Solution 1 - Revert to previous version
You could revert back to 6.3.0
though by running npm i -s [email protected]
to install that exact version. Double-check your package.json file to ensure the entry is "react-router-dom": "6.3.0"
.
Solution 2 - Use the "real" history
object
If you wanted to move forward with the newer RRD versions then an alternative I'd suggest is to use the history@5
history
object directly instead of trying to use the react-router@6
navigator
. RRDv6 was only ever exporting a subset of the history
methods anyway.
Add
history@5
as a project dependency.IMPORTANT: You will want to check what version
react-router-dom
is using and match if you can.Create and export a custom history object.
createBrowserHistory
for a BrowserRouter,createHashHistory
for a HashRouter, etc.import { createBrowserHistory } from 'history'; const history = createBrowserHistory(); export default history;
Import your custom history object and the history router from RRD.
import { unstable_HistoryRouter as Router } from "react-router-dom"; import history from './history'; ... <Router history={history}> <App /> </Router>
Import your custom history object to use in your custom hooks.
import { useCallback, useEffect, useState } from "react"; import { useNavigate, useLocation } from "react-router-dom"; import history from "./history"; // <-- import const useBlocker = (blocker, when = true) => { useEffect(() => { if (!when) return; const unblock = history.block((tx) => { // <-- use history const autoUnblockingTx = { ...tx, retry() { unblock(); tx.retry(); } }; blocker(autoUnblockingTx); }); return unblock; }, [blocker, when]); };
useCallbackPrompt
is untouched.const useCallbackPrompt = (when) => { const navigate = useNavigate(); const location = useLocation(); const [showPrompt, setShowPrompt] = useState(false); const [lastLocation, setLastLocation] = useState(null); const [confirmedNavigation, setConfirmedNavigation] = useState(false); const cancelNavigation = useCallback(() => { setShowPrompt(false); }, []); const handleBlockedNavigation = useCallback( (nextLocation) => { if ( !confirmedNavigation && nextLocation.location.pathname !== location.pathname ) { setShowPrompt(true); setLastLocation(nextLocation); return false; } return true; }, [confirmedNavigation] ); const confirmNavigation = useCallback(() => { setShowPrompt(false); setConfirmedNavigation(true); }, []); useEffect(() => { if (confirmedNavigation && lastLocation) { navigate(lastLocation.location.pathname); } }, [confirmedNavigation, lastLocation]); useBlocker(handleBlockedNavigation, when); return [showPrompt, confirmNavigation, cancelNavigation]; };
Demo
From v6.4.0 navigator.block is removed. You can find a workaround here: https://gist.github./MarksCode/64e438c82b0b2a1161e01c88ca0d0355.
Also, relevant discussion going on here. https://github./remix-run/react-router/issues/8139#issuement-1262630360
In v6.7.0 they added unstable_useBlocker
and unstable_usePrompt
and those are still there.
So you can either use unstable_usePrompt
directly or if you want some custom ponent to be shown you can try to bine your custom solution with unstable_useBlocker
.
I did this in my case:
export function usePrompt(when = true) {
const blocker = unstable_useBlocker(when);
useEffect(() => {
// message in latest Chrome will be ignored anyway - it uses its own
if (when) window.onbeforeunload = () => "Are you sure?";
return () => {
window.onbeforeunload = null;
};
}, [when]);
useEffect(() => {
if (blocker.state === "blocked") {
const element = document.createElement("div");
element.setAttribute("id", "prompt-dialog-container");
element.setAttribute("aria-hidden", "true");
const closePrompt = (state: boolean) => {
if (element) {
ReactDOM.unmountComponentAtNode(element);
}
if (!state) {
document.body.removeChild(element);
blocker.reset();
} else {
blocker.proceed();
}
};
document.body.appendChild(element);
// just a modal with message "You have unsaved changes in this report. Do you want to save your changes?" and 2 buttons [Yes] and [No]
ReactDOM.render(<ExitPrompt onYes={() => closePrompt(false)} onNo={() => closePrompt(true)} />, element);
}
}, [blocker]);
}