Fix: created hook for useScrollToTop to reuse functionallity and util for getSortedHotels

This commit is contained in:
Pontus Dreij
2024-12-12 14:37:41 +01:00
parent 50fc8a183c
commit c2b4d8abcf
4 changed files with 85 additions and 80 deletions

33
hooks/useScrollToTop.ts Normal file
View File

@@ -0,0 +1,33 @@
import { type RefObject,useEffect,useState } from "react"
interface UseScrollToTopProps {
threshold: number
elementRef?: RefObject<HTMLElement>
}
export function useScrollToTop({ threshold, elementRef }: UseScrollToTopProps) {
const [showBackToTop, setShowBackToTop] = useState(false)
useEffect(() => {
const element = elementRef?.current ?? window
function handleScroll() {
const scrollTop = elementRef?.current
? elementRef.current.scrollTop
: window.scrollY
setShowBackToTop(scrollTop > threshold)
}
element.addEventListener("scroll", handleScroll, { passive: true })
return () => element.removeEventListener("scroll", handleScroll)
}, [threshold, elementRef])
function scrollToTop() {
if (elementRef?.current)
elementRef.current.scrollTo({ top: 0, behavior: "smooth" })
else window.scrollTo({ top: 0, behavior: "smooth" })
}
return { showBackToTop, scrollToTop }
}