Sorry if this has been already answered.
But is there a way to execute a custom function on every <Link>
navigation? Preferably without creating a custom <Link>
wrapper.
I'd like to put some information to sessionStorage before every navigation inside my application.
Thanks
You can use onClick
to perform any action, say
<Link
to="/"
onClick={() => console.log('Heading to /')} />
Replace console.log
with a function that would perform sessionStorage
update and such, and that's it.
Another way would be to use onEnter
prop of Route
component to execute a certain function per every route enter:
<Route
path="/"
component={App}
onEnter={() => console.log('Entered /')} />
See the reference, or example with react-router and react-redux.
I was literally looking for this answer and couldn't find it anywhere and then I did some experimenting and this was my answer that helped me, so I thought I'd share!
If you use the uselocation hook by React Router. This hook gives you an object with a key property that changes on every router change. You can then create a useEffect that watches for this property and fire a function when that key changes. See example below
const location = useLocation();
useEffect(() => {
console.log('location', location.key); // { key: "3uu089" }
// Fire whatever function you need.
sessionStorage.setItem('whatever', state);
}, [location.key]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With