How to restore the scroll position
Unanswered
Carpenter ant posted this in #help-forum
Carpenter antOP
How to restore the scroll position when navigating back in the browser? I used this library before, but it doesn't support the new app router https://github.com/moxystudio/next-router-scroll#readme
I found such a solution, but it uses an event that is also not supported in the new router - routeChangeStart
I found such a solution, but it uses an event that is also not supported in the new router - routeChangeStart
import { useEffect } from 'react';
import { useRouter } from 'next/router';
export default function Home() {
const router = useRouter();
// set scroll restoration to manual
useEffect(() => {
if ('scrollRestoration' in history && history.scrollRestoration !== 'manual') {
history.scrollRestoration = 'manual';
}
}, []);
// handle and store scroll position
useEffect(() => {
const handleRouteChange = () => {
sessionStorage.setItem('scrollPosition', window.scrollY.toString());
};
router.events.on('routeChangeStart', handleRouteChange);
return () => {
router.events.off('routeChangeStart', handleRouteChange);
};
}, [router.events]);
// restore scroll position
useEffect(() => {
if ('scrollPosition' in sessionStorage) {
window.scrollTo(0, Number(sessionStorage.getItem('scrollPosition')));
sessionStorage.removeItem('scrollPosition');
}
}, []);
return (
<>
...Put your HTML or components for your page here...
</>
);
}