Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforcing scrollToTop behavior using React Router

I would like to have the user's scroll position default to the top of the page upon transitions.

For example, clicking on a <Link> element on the footer pushes the user into view that's scrolled all the way down, where the footer is.

Is there an option to set all transitions to display the new component from the top?

like image 429
robinnnnn Avatar asked Dec 17 '15 22:12

robinnnnn


2 Answers

React Router versions <4

You can also simply add an onUpdate attribute to your <Router> like so:

<Router onUpdate={() => window.scrollTo(0, 0)} history={history}>
  // routes
</Router>

React Router version 4

In the new React Router version, you can create a ScrollToTop component like this (adapted from the docs here):

// ScrollToTop.js    
import React, {Component} from 'react'
import {withRouter} from 'react-router-dom'

class ScrollToTop extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0)
    }
  }

  render() {
    return <div>{this.props.children}</div>
  }
}

export default withRouter(ScrollToTop)

And then you use it by adding it immediately below your BrowserRouter/Router component like this:

// App.js
import React, {Component} from 'react';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom'
import ScrollToTop from './ScrollToTop'

const App = () => (
  <Router>
    <ScrollToTop>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Link to="/">Home</Link>{' '}
      <Link to="/about">About</Link>
    </ScrollToTop>
  </Router>
)
like image 105
Sia Avatar answered Oct 03 '22 21:10

Sia


You need to import the scroll-behavior lib, designed for use with react router. Here's how you use it:

import createHistory from 'history/lib/createBrowserHistory';
import useScrollToTop from 'scroll-behavior/lib/useScrollToTop';

const history = useScrollToTop(createHistory)();

Then pass the history object as the history prop to your Router.

The above code snippet - modified to import useScrollToTop instead of useStandardScroll - was taken from here: https://github.com/rackt/scroll-behavior

like image 35
David L. Walsh Avatar answered Oct 03 '22 22:10

David L. Walsh