Last active
July 24, 2024 10:11
-
-
Save icodeforlove/2ac02951a77ae9576a496a90feece923 to your computer and use it in GitHub Desktop.
ScrollRestoration for React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use client'; | |
import { useEffect } from 'react'; | |
function ScrollRestoration() { | |
useEffect(() => { | |
const pushState = history.pushState; | |
history.pushState = function (data, unused, url) { | |
const scrollY = window.scrollY; | |
// Save the current scroll position in the state before navigating | |
history.replaceState({ ...history.state, _scrollY: scrollY }, ''); | |
return pushState.call(history, data, unused, url); | |
}; | |
const handlePopState = (event: PopStateEvent) => { | |
if (event.state?._scrollY) { | |
const scrollY = event.state._scrollY; | |
setTimeout(() => { | |
if (window.scrollY !== scrollY) { | |
window.scrollTo(0, scrollY); | |
} | |
}, 0); | |
} | |
}; | |
window.addEventListener('popstate', handlePopState); | |
return () => { | |
history.pushState = pushState; | |
window.removeEventListener('popstate', handlePopState); | |
}; | |
}, []); | |
return null; | |
} | |
export default ScrollRestoration; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Are you using other things related to scroll?
This requires you to turn off all the scroll helpers as it will handle scroll positioning on its own.
Also this was only tested to work with pages with scrollbars on the main scroll (not sub elements, but could be adapted to do that as well).