Event Listener on Navigation with react router v6
Asked Answered
C

2

8

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 comming from.

Chaffin answered 3/3, 2022 at 8:29 Comment(2)
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 the Prompt component will be added back into v6 (reactrouter.com/docs/en/v6/upgrading/…).Neiman
If you need help with the custom router, my answer here can help get you going in the right direction.Neiman
C
7

You can useLocation() and useEffect().

const location = useLocation();
useEffect(() => {
   console.log("url changed")
}, [location]);
Cisco answered 3/3, 2022 at 8:34 Comment(4)
Does this prevent the navigation? I want to use this to interrupt the navigate action and route to another url, depending where the user is comming fromChaffin
No, this listens to changes. So please be more specific about what you need in your question.Cisco
Yeah thats my bad. Added the informationChaffin
I’m looking for the same thing but BEFORE the navigation event occurs. This is for after. Is there a hook available for before navigation?Contemporaneous
A
0

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

Arlenearles answered 9/4, 2023 at 20:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.