Merged in chore/move-use-scroll-to-top (pull request #2705)
chore: Move useScrollToTop to common package * Move useScrollToTop to common package Approved-by: Joakim Jäderberg
This commit is contained in:
@@ -1,46 +0,0 @@
|
||||
import { type RefObject, useEffect, useState } from "react"
|
||||
|
||||
interface UseScrollToTopProps {
|
||||
threshold: number
|
||||
elementRef?: RefObject<HTMLElement | null>
|
||||
refScrollable?: boolean
|
||||
}
|
||||
|
||||
export function useScrollToTop({
|
||||
threshold,
|
||||
elementRef,
|
||||
refScrollable,
|
||||
}: UseScrollToTopProps) {
|
||||
const [showBackToTop, setShowBackToTop] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const element =
|
||||
refScrollable && elementRef?.current ? elementRef?.current : window
|
||||
|
||||
function handleScroll() {
|
||||
let position = window.scrollY
|
||||
if (elementRef?.current) {
|
||||
position = refScrollable
|
||||
? elementRef.current.scrollTop
|
||||
: elementRef.current.getBoundingClientRect().top * -1
|
||||
}
|
||||
setShowBackToTop(position > threshold)
|
||||
}
|
||||
|
||||
element.addEventListener("scroll", handleScroll, { passive: true })
|
||||
return () => element.removeEventListener("scroll", handleScroll)
|
||||
}, [threshold, elementRef, refScrollable])
|
||||
|
||||
function scrollToTop() {
|
||||
if (elementRef?.current) {
|
||||
if (refScrollable) {
|
||||
elementRef.current.scrollTo({ top: 0, behavior: "smooth" })
|
||||
}
|
||||
window.scrollTo({ top: elementRef.current.offsetTop, behavior: "smooth" })
|
||||
} else {
|
||||
window.scrollTo({ top: 0, behavior: "smooth" })
|
||||
}
|
||||
}
|
||||
|
||||
return { showBackToTop, scrollToTop }
|
||||
}
|
||||
Reference in New Issue
Block a user