umami/hooks/useSticky.js

28 lines
762 B
JavaScript
Raw Normal View History

2023-02-09 08:14:11 +01:00
import { useState, useEffect, useRef } from 'react';
2023-02-10 12:26:57 +01:00
export default function useSticky({ scrollElementId, 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(() => {
2023-02-10 12:26:57 +01:00
const element = scrollElementId ? document.getElementById(scrollElementId) : window;
2023-02-09 08:14:11 +01:00
const handleScroll = () => {
2023-02-09 17:22:36 +01:00
setIsSticky(element.scrollTop > 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
2023-02-09 17:22:36 +01:00
element.addEventListener('scroll', handleScroll);
2023-02-09 08:14:11 +01:00
return () => {
2023-02-09 17:22:36 +01:00
element.removeEventListener('scroll', handleScroll);
2023-02-09 08:14:11 +01:00
};
2023-02-10 12:26:57 +01:00
}, [ref, setIsSticky]);
2023-02-09 08:14:11 +01:00
return { ref, isSticky };
}