I would like to add an event listener to a navigate
event in react router v6. I have not found anything to it. Is there such a feature?
Edit: When the event is handled, I want to prevent the navigation and route the user to another destination, which depends on where he is ming from.
I would like to add an event listener to a navigate
event in react router v6. I have not found anything to it. Is there such a feature?
Edit: When the event is handled, I want to prevent the navigation and route the user to another destination, which depends on where he is ming from.
Share Improve this question edited Mar 3, 2022 at 8:48 CrystalCase asked Mar 3, 2022 at 8:29 CrystalCaseCrystalCase 1971 gold badge2 silver badges13 bronze badges 2-
1
There is no straight forward way to do this in RRDv6. You could create a custom router and history object so you can use
history.block
. Perhaps at some point thePrompt
ponent will be added back into v6 (reactrouter./docs/en/v6/upgrading/…). – Drew Reese Commented Mar 3, 2022 at 9:00 - If you need help with the custom router, my answer here can help get you going in the right direction. – Drew Reese Commented Mar 3, 2022 at 9:37
4 Answers
Reset to default 8You can useLocation()
and useEffect()
.
const location = useLocation();
useEffect(() => {
console.log("url changed")
}, [location]);
You might get away with just using the navigate function once the location changes
const location = useLocation();
const navigate = useNavigate();
useEffect(() => {
navigate("/home") // enter your route here
}, [location]);
this will look very ugly for the user tho
If you just want to block the navigation there is a new hook in react-router v6 called useBlocker
, which can be used to display an alert when the specified boolean is true. Refer to React Router Dom - v6 - useBlocker issue here
You are looking for useBlocker
:
The useBlocker hook allows you to prevent the user from navigating away from the current location, and present them with a custom UI to allow them to confirm the navigation.
Once the navigation is blocked, the page can continue to navigate to the desired path.
i do this in every of my project, useBlocker
might be unstable and not controlled in production environment, so i don't use it.
i have a custom hook which i reuse in cases like this
import { useNavigate, useLocation } from 'react-router-dom';
export const useCustomNavigate = () => {
const navigate = useNavigate();
const location = useLocation();
const customNavigate = (target: string) => {
// prevent navigation if ing from a specific path.
if (location.pathname === '/restricted') {
// Route to an alternate destination you want
navigate('/alternate', { replace: true });
} else {
navigate(target);
}
};
return customNavigate;
};
reuse in your other ponent this way
const customNavigate = useCustomNavigate();
return (
<button onClick={() => customNavigate('/dashboard')}>Go to Dashboard</button>
)