Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
198
rated 0 times [  199] [ 1]  / answers: 1 / hits: 18655  / 4 Years ago, mon, march 23, 2020, 12:00:00

I'm currently trying to scroll to top on page refresh. So far I've been able to implement scroll to top on route change, but not on page refresh - somehow react always restores its previous position. How can I prevent that from happening?



That's how I implemented scroll to top (thought window.scrollTo(0, 0) inside of componenDidMount() would help, but it didn't):



class ScrollToTop extends Component {

componentDidMount() {
window.scrollTo(0, 0);
}

componentDidUpdate(prevProps, prevState, snapshot) {
if (this.props.location.pathname !== prevProps.location.pathname) {
window.scrollTo(0, 0);
}
}

render() {
return null;
}
}

export default withRouter(ScrollToTop);


class App extends Component {

render() {
return (
<BrowserRouter>
<ScrollToTop/>
<Header/>
<Home/>
<Projects/>

<div className=follow-cursor/>
</BrowserRouter>
);
}
}

export default App;

More From » reactjs

 Answers
5

EDIT


this answer is a better approach for this problem since its using react hooks instead of pure-js all over the place.


ORIGINAL


You can use some pure JS for that:


window.onbeforeunload = function () {
window.scrollTo(0, 0);
}

This will make page scroll to top before it reloads, so everything will be fine when reload ends.


[#51112] Thursday, March 12, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
megb

Total Points: 230
Total Questions: 113
Total Answers: 100

Location: Tokelau
Member since Sun, May 7, 2023
1 Year ago
;