Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router: execute custom function on every <Link> navigation

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

like image 739
Matúš Čongrády Avatar asked Sep 02 '16 14:09

Matúš Čongrády


2 Answers

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.

like image 158
rishat Avatar answered Sep 30 '22 16:09

rishat


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]);
like image 43
Christoph Codes Avatar answered Sep 30 '22 17:09

Christoph Codes