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

Upvotes: 20

Views: 39176

Answers (3)

Christoph Codes
Christoph Codes

Reputation: 171

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]);

Upvotes: 16

Kevin Kiwango
Kevin Kiwango

Reputation: 99

You can call any function on the route object of react router like the below:

function someFunction(a,b){ 
 const c = a + b;
 return c
} 


<Switch>
  <Route exact exact path="/" component={SomeComponent} />
  <Route path="/reload" render= {(props)=>someFunction() } />
</Switch>

Upvotes: -2

rishat
rishat

Reputation: 8376

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.

Upvotes: 25

Related Questions