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?
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>
)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With