umami/hooks/useSticky.js

26 lines
747 B
JavaScript
Raw Normal View History

2023-02-09 08:14:11 +01:00
import { useState, useEffect, useRef } from 'react';
export default function useSticky({ scrollElement = document, defaultSticky = false }) {
2023-02-09 08:14:11 +01:00
const [isSticky, setIsSticky] = useState(defaultSticky);
const ref = useRef(null);
2023-02-09 17:22:36 +01:00
const initialTop = useRef(null);
2023-02-09 08:14:11 +01:00
useEffect(() => {
const handleScroll = () => {
setIsSticky((scrollElement?.scrollTop ?? window.scrollY) > initialTop.current);
2023-02-09 08:14:11 +01:00
};
2023-02-09 17:22:36 +01:00
if (initialTop.current === null) {
2023-02-10 12:26:57 +01:00
initialTop.current = ref?.current?.offsetTop;
2023-02-09 17:22:36 +01:00
}
2023-02-09 08:14:11 +01:00
scrollElement.addEventListener('scroll', handleScroll, true);
2023-02-09 08:14:11 +01:00
return () => {
scrollElement.removeEventListener('scroll', handleScroll, true);
2023-02-09 08:14:11 +01:00
};
2023-03-04 06:26:39 +01:00
}, [ref, setIsSticky, scrollElement]);
2023-02-09 08:14:11 +01:00
return { ref, isSticky };
}