React router: execute custom function on every 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

1

3 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.

7

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

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> 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like