import { useRef, useEffect } from 'react';
import { IonContent } from '@ionic/react';
const contentRef = useRef<HTMLIonContentElement>(null);
<IonContent ref={contentRef} style={{ overscrollBehavior: 'contain' }}>
...
</IonContent>
Use useEffect hook to add the overscroll effect after the component has mounted:
useEffect(() => {
const contentElement = contentRef.current;
if (contentElement) {
contentElement.addEventListener('touchmove', handleTouchMove, { passive: false });
}
return () => {
if (contentElement) {
contentElement.removeEventListener('touchmove', handleTouchMove);
}
};
}, []);
const handleTouchMove = (event: TouchEvent) => {
const contentElement = contentRef.current;
if (contentElement) {
const scrollTop = contentElement.scrollTop;
const scrollHeight = contentElement.scrollHeight;
const height = contentElement.clientHeight;
const delta = event.touches[0].clientY - startY;
const offset = contentElement.offsetHeight - contentElement.scrollHeight;
if (scrollTop === 0 && delta > 0) {
event.preventDefault();
contentElement.style.transform = `translate3d(0, ${delta}px, 0)`;
} else if (scrollTop === scrollHeight - height && delta < 0) {
event.preventDefault();
contentElement.style.transform = `translate3d(0, ${delta}px, 0)`;
}
if (contentElement.style.transform !== '' && Math.abs(delta) > 50) {
contentElement.style.transition = 'transform 0.3s ease-out';
}
}
};
This code assumes that you have defined startY
somewhere.
Note: The overscroll effect can negatively impact performance on some devices, so use it sparingly and test on multiple devices before implementing it in production.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-07-18 00:54:56 +0000
Seen: 8 times
Last updated: Jul 18 '23