2023-02-09 08:14:11 +01:00
|
|
|
import { useState, useEffect, useRef } from 'react';
|
|
|
|
|
2023-03-03 21:37:26 +01:00
|
|
|
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 = () => {
|
2023-03-03 21:37:26 +01:00
|
|
|
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
|
|
|
|
2023-03-03 21:37:26 +01:00
|
|
|
scrollElement.addEventListener('scroll', handleScroll, true);
|
2023-02-09 08:14:11 +01:00
|
|
|
|
|
|
|
return () => {
|
2023-03-03 21:37:26 +01:00
|
|
|
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 };
|
|
|
|
}
|