I've seen numerous questions on this topic but no one of them seem to go about it my way. They usually involve window scrolling. I have a div with items that can overflow and I want to remember the scroll that the user left. I save this in the local storage but I've been unable to get the correct scroll position. (The items are in hundreds)
const ItemHolder = ({
shouldScroll, // this indicates whether or not we should load the previous scroll from the storage
searchParams,
}: ItemHolderProps) => {
const [items, setItems] = useImmer<Item[]>([]);
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => { // HERE WE SHOULD GET THE SCROLL VALUE WHEN UNMOUNTING
const scroll = scrollRef.current; // this is because we don't have access to ref.current in unmount
return () => {
if (scroll) {
// doesn't work
const winScroll = scroll.scrollTop;
const height = scroll.scrollHeight - scroll.clientHeight;
const scrolled = winScroll / height;
localStorage.setItem("scroll", String(scrolled));
}
};
}, []);
useEffect(() => {
const scroll = scrollRef.current;
const scrollAmountStorage = localStorage.getItem("scroll");
let scrollTop = 0;
if (scrollAmountStorage) {
scrollTop = Number(scrollAmountStorage);
}
if (shouldScroll && scroll) {
console.log("Scroll top : ", scrollTop);
scroll.scrollTo({ top: scrollTop });
}
}, [shouldScroll]);
return (
<div
// onScroll={(e) => {
// console.log(e);
// }}
ref={scrollRef}
className="grid grid-cols-2 mx-auto p-2 gap-3 overflow-x-auto h-full"
>
{items.map((i) => (
<Item key={i.id} />
))}
</div>
);
};
Basically what confuses me is that there is no intuitive and straightforward way to get the current scroll and then just apply it again. All of the SO answers I've found used these kinds of calculations with windows.height and such.