React-Router onChange hook

18,292

onUpdate needs to be declared on the Router instance not Routes. Although, Routes can declare onChange and onEnter hooks - it's probably what you were looking for.

Share:
18,292

Related videos on Youtube

Martial
Author by

Martial

Updated on September 15, 2022

Comments

  • Martial
    Martial over 1 year

    I am having issues getting the onChange hook in react-router to work properly. Here is my routes file:

    import React from 'react';
    import { Router, Route, browserHistory } from 'react-router';
    import TestOne from './Pages/testone';
    import TestTwo from './Pages/testtwo';
    
    function logUpdate() {
        console.log('Current URL: ' + window.location.pathname);
    }
    
    const Routes = (
        <Router history={browserHistory}>
            {/* App Routes */}
            <Route path="/" component={App} lang={lang}>
                <Route path="/testone" component={TestOne} onUpdate={logUpdate} />
                <Route path="/testtwo" component={TestTwo} onUpdate={logUpdate} />
            </Route>
        </Router>);
    
    export default Routes;
    

    My understanding is, that the function logUpdate will be triggered on each state change. However, it is only triggered when I reload the corresponding page via F5.

    My menu is using simple Links e.g.:

    <div>
    <Link to="/testone">Test One</Link>
    <Link to="/testtwo">Test Two</Link>
    </div>
    

    What am I doing wrong?

  • Martial
    Martial over 7 years
    Great, can't believe I've missed that! Thanks Igorsvee
  • Marwen Trabelsi
    Marwen Trabelsi over 6 years
    These links are for version 2.X, now react-router on 4.0 :)
  • Gyro
    Gyro over 5 years
    on version 4 onUpdate was removed from Router component. See this question - stackoverflow.com/questions/41911309/…