33 lines
956 B
TypeScript
33 lines
956 B
TypeScript
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 }
|
|
}
|