make sure a page loads at the top react code example
Example 1: scroll to top in react
componentDidMount() {
window.scrollTo(0, 0)
}
Example 2: handling scrolling on react router transitions
import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
return (null);
}
export default withRouter(ScrollToTop);