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:
Anton Gunnarsson
2025-08-26 11:48:54 +00:00
parent 4c3ddea5c0
commit c53e6ef187
13 changed files with 13 additions and 14 deletions

View File

@@ -0,0 +1,46 @@
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 }
}