Fix: created hook for useScrollToTop to reuse functionallity and util for getSortedHotels
This commit is contained in:
33
hooks/useScrollToTop.ts
Normal file
33
hooks/useScrollToTop.ts
Normal 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 }
|
||||
}
|
||||
Reference in New Issue
Block a user