I’ve implemented this effect custom React Hook without using any other module.
I added a hook code and an example.
// Hook
export const useScroll = () => {
const [visible, setVisible] = useState(false);
const ref = useRef<any>(null);
const checkVisible = () => {
const offset = ((element) => {
let offset = 0;
while (element) {
offset += element.offsetTop;
element = element.offsetParent;
}
return offset;
})(ref.current);
const scrollY = window.scrollY;
if (offset - scrollY > (window.innerHeight * 3) / 4) return false;
else return true;
};
useEffect(() => {
setVisible(checkVisible());
const scrollHandler = (_: Event) => {
setVisible(checkVisible());
};
window.addEventListener("scroll", scrollHandler);
return () => {
window.removeEventListener("scroll", scrollHandler);
};
}, []);
return { visible, element: ref };
};
// Example
export const Item = () => {
const { visible, element } = useScroll();
return (
<Div
visibility={visible ? "visible" : "hidden"}
opacity={visible ? "1" : "0"}
transition={"500ms"}
transform={
visible ? "scale(1) translateY(0%)" : "scale(0.8) translateY(100%)"
}
ref={element}
>
...
Please share if there’s any better way to implement it so easily.
My solution has some problems when the items are so many.
If you have a better way to easily implement this, please share.
My solution has some problems if there are too many items, because it add so many event listeners.
New contributor
Atos F. is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.