menu
announcement

Spectrum will become read-only on August 10, 2021. Learn more about the decision in our official announcement.

React

A community of developers, designers and others who love React.js. ⚛️

Channels
Team

Handling scroll position on route changes

October 26, 2018 at 8:55am

Handling scroll position on route changes

October 26, 2018 at 8:55am
Has anyone found a good way of handling scroll position in a nice way with react-router?
I think a good solution would:
  • Scroll to top when clicking a link
  • Return the user to the previous scroll postion on clicking the browser back/forward-button
Any tips?

October 26, 2018 at 11:01am
, maybe store the position for the url in, redux or mobx or something else.. and then attach a component like this to the React Router
  • reply
  • like
store the y postion for the url into a store.
and then add something like this to the router
```const ScrollToTop = () => {
const y = getPostForUrl()
window.scrollTo(y, 0);
return null;
};
and then add it to the router
<Route component={ScrollToTop} />```
  • reply
  • like
Yeah, this is quite similar to the approach we’re currently using:
class ScrollToTop extends React.Component {
// Remembers scroll positions based on location->key
scrollPositions = {}
componentWillMount() {
if ("scrollRestoration" in window.history) {
window.history.scrollRestoration = "manual"
}
window.scrollTo(0, 0)
}
componentDidUpdate(prevProps) {
const {
history: { action },
location: { pathname: newPath = "root" }
} = this.props
const {
location: { pathname = "root" }
} = prevProps
if (action === "POP") {
const pos = this.scrollPositions[newPath]
if (pos) {
setTimeout(() => window.scrollTo(pos[0], pos[1]), 50)
}
} else {
this.scrollPositions[pathname] = [window.pageXOffset, window.pageYOffset]
setTimeout(() => window.scrollTo(0, 0), 50)
}
}
render() {
return null
}
}
export default withRouter(ScrollToTop)
like-fill
3
  • reply
  • like
yes,
why is code formatting not working on my posts ?! 😰
  • reply
  • like

October 29, 2018 at 1:24pm
I think you need to type ```
  • reply
  • like
and then shift + enter, to get the code-block to show
  • reply
  • like

December 23, 2018 at 3:04pm
Hi. Does anyone knows why would it throw an error sayin 'withRouter not defined'?? i can't get this to work.
  • reply
  • like

December 28, 2018 at 3:17pm
Hi. Does anyone knows why would it throw an error sayin 'withRouter not defined'?? i can't get this to work.
You need to import withRouter at the top of file before you declare your ScrollToTop component.
import { withRouter } from "react-router";
Edited
  • reply
  • like
Scroll to top when clicking a link
Return the user to the previous scroll postion on clicking the browser back/forward-button
isn't that browser native behaviour already?
Edited
  • reply
  • like