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; |
IDK why but I'm testing this and it's scrolling the wrong page. Like I start on Page A, go to Page B, Scroll Down, go back to Page A, and Page A is scrolled down now
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).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This solution was tested with Next.js v15.
I encountered an issue where some components would cause the user to jump back to the top of the page when clicking the back button.
To resolve this, I monkey-patched the
.pushState
method. The patch runs a.replaceState
to add a_scrollY
position before executing the original.pushState
.When the user triggers a
popState
by going back, the script checks if the state being popped has a_scrollY
property. If it does, it triggers ascrollTo
on the next event loop.This approach worked for me.