Let’s say I have two pages/two routes. In one I have a <Link>
component:
<Link to="/something">
<Button>
This is Link
</Button>
</Link>
In the second, I can go back to the previous route:
const handleGoBack = () => {
navigate(-1);
};
return (
<Button onClick={handleGoBack}>
Back
</Button>
);
What is the best way to save the position of the first page to where I clicked that <Link>
component, so that when I navigate back from another page, I should return to the exact position I clicked the link from?
I tried adding this to the first component:
function storeScrollPosition() {
sessionStorage.setItem('scrollPosition', window.scrollY.toString());
}
And then I use that in the <Link>
as onClick
action:
<Link to="/something" onClick={storeScrollPosition}>
<Button>
This is Link
</Button>
</Link>
, while doing all logic in useEffect
in the second component:
useEffect(() => {
const scrollPosition = sessionStorage.getItem('scrollPosition');
if (scrollPosition) {
window.scrollTo(0, parseInt(scrollPosition));
sessionStorage.removeItem('scrollPosition');
} else {
window.scrollTo(0, 0);
}
}, []);
But it seems that it’s not working perfectly. Sometimes it works, sometimes it doesn’t work. I don’t know, but I think it has something to do with page rendering. Is there by chance any better way to do this?
*I use react-router-dom for navigation.