Issue
I encountered the strangest problem today. My code (much has been stripped out) consists of basically the following:
const Element: React.FC<any> = (props: any) => {
const scrollRef = React.useRef<any>(null);
.
.
.
const rescrollTrigger = () => {
setTimeout(() => { /* Retry for 10 seconds to scroll the content to match the stored value, unless the user has scrolled since then */
const cb = (tries: number) => {
if (tries > 100)
return;
if (!scrollRef.current) {
setTimeout(cb, 100, [Number(tries) + 1]);
return;
}
scrollRef.current.getScrollElement().then((element: any) => {
var scrollHeight: any = window.sessionStorage.getItem(thisPath + "/scrollheight");
var scrollTop: any = window.sessionStorage.getItem(thisPath + "/scrolltop");
if (!scrollHeight || !scrollTop)
return;
scrollHeight = +scrollHeight;
scrollTop = +scrollTop;
if (element.scrollHeight == scrollHeight)
scrollRef.current.scrollToPoint(0, scrollTop);
else
setTimeout(cb, 100, [Number(tries) + 1]);
}).catch(() => {
setTimeout(cb, 100, [Number(tries) + 1]);
})
};
window.requestAnimationFrame(() => {
cb(1);
});
});
};
const saveScrollPosition = () => {
console.log("saveScrollPosition", scrollRef.current);
try {
scrollRef.current.getScrollElement().then((element: any) => {
console.log("Saving scroll position");
window.sessionStorage.setItem(thisPath + "/scrolltop", String(element.scrollTop));
window.sessionStorage.setItem(thisPath + "/scrollheight", String(element.scrollHeight));
});
} catch (err) {console.log("Error saving scroll position", err)}
};
return (
<IonPage>
<IonContent fullscreen ref={scrollRef} scrollEvents={true} onIonScrollEnd={e => saveScrollPosition()}>
.
.
.
}
I'm just trying to create a ref (in a hook) to the content instance so I can save and reset the scroll position as needed.
This code was working fine, but for some reason stopped triggering any scroll events if a ref is set on the content element. I've tried onIonScroll and onIonScrollEnd. Neither work if a ref is set. Removing the ref={scrollRef} starts triggering the scroll events. I'm using Ionic 6.12.2 and just recently upgraded from a prior version (I don't know what it was).
So my question is: Is this a bug in Ionic? Or if not, what should be done to fix the code? I've tried not setting a ref and just using the target returned from the scroll event, which allows me to save the position, but it doesn't preserve a reference to be able to reset the scroll position later.
Solution
This looks like an Ionic bug. Ionic 6.12.3 allows the event to fire with a ref and the behavior is not reproducible.
Answered By - owacoder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.