5

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.

CrystalCase
  • 137
  • 2
  • 11
  • 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`](https://github.com/remix-run/history/blob/main/docs/api-reference.md#historyblockblocker-blocker). Perhaps at some point the `Prompt` component will be added back into v6 (https://reactrouter.com/docs/en/v6/upgrading/v5#prompt-is-not-currently-supported). – Drew Reese Mar 03 '22 at 09:00
  • If you need help with the custom router, my [answer here](https://stackoverflow.com/a/70000286/8690857) can help get you going in the right direction. – Drew Reese Mar 03 '22 at 09:37

2 Answers2

5

You can useLocation() and useEffect().

const location = useLocation();
useEffect(() => {
   console.log("url changed")
}, [location]);
Jax-p
  • 7,225
  • 4
  • 28
  • 58
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