9

I have recently updated to react router version 4. In the previous version I was using the onUpdate call back to trigger a function to make the page scroll to the top when the route has been changed.

It appears that onUpdate has been deprecated and I cannot find anywhere in the docs what it has been replaced with.

Has anyone else come across this issue?

const handlePageChange = () => {
    window.scrollTo(0, 0);
};  

ReactDOM.render(
    <Provider store={store}>
        <Router onUpdate={handlePageChange} history={browserHistory}>
            <Redirect from="/" to="/music" />
            {routes}
        </Router>
    </Provider>,
    document.getElementById('root')
);
peter flanagan
  • 6,130
  • 13
  • 50
  • 94

4 Answers4

3

"onUpdate" is depreciated. You can use "onEnter" property in "Routes".

<Router history={browserHistory}>
  <Route path="/" component={App} >
    <IndexRoute component={Home} />
    <Route path="/contact-us" component={ContactUs} onEnter={handlePageChange}/>
  </Route>
</Router>

Also need to modify your "handlePageChange" function as below:

const handlePageChange = () => {
    window.scrollTo(0, 0);
    if ('scrollRestoration' in history) {
        history.scrollRestoration = 'manual';
    }
}
Tanmay Verma
  • 245
  • 1
  • 3
  • 12
1

@Alireza's answer was in the right direction, but it's not quite complete.

To be able to access the router in using React's Context API, the component both has to be a child of the Router, and it should define the contextTypes property:

static contextTypes = {
  router: PropTypes.object
};

That will make sure that the Router is attached to that component.

Furthermore, you can not (or no longer?) subscribe to the router. However, you can attach a listener to the History:

this.context.router.history.listen(handlePageChange)

You'll probably want to do that in the component's componentDidMount lifecycle method.

Vincent
  • 3,523
  • 2
  • 34
  • 47
1

Another option is to scroll the page when your page component mounts:

class NotFoundView extends React.Component {
  componentDidMount() {
    window.scrollTo(0, 0);
  }

  render() {
    var props = this.props;

    return (
      <div className="NotFound">
        <HeaderContainer />

        <h1>Coming Soon!</h1>
      </div>
    )
  }
}

export default NotFoundView;
Eric Rowell
  • 5,039
  • 21
  • 22
0

There is something called context.router.subscribe as replacement...

you can use something like this:

import React from 'react';

class App extends React.Component {
  //something like this in your code
  componentDidMount() {
    this.context.router.subscribe(() => {
        console.log("change router");
    })
   }
    render() {
    return <button>hi</button>;
  }
}

export default App;
Alireza
  • 83,698
  • 19
  • 241
  • 152