Loading...
Please waitLoading...
Please waitScroll the window or a specific element to the top with the useScrollToTop hook, providing options for smooth scrolling and custom behavior.
pnpm dlx uselab@latest add use-scroll-to-top
import { useScrollToTop } from "@/hooks/use-scroll-to-top"
export function Component() {
const scrollToTop = useScrollToTop({
target: window, // Element to scroll, defaults to window
behavior: "smooth", // Scrolling behavior, can be "auto" or "smooth"
})
return (
<div style={{ padding: "20px", maxWidth: "600px", margin: "0 auto" }}>
<p>Click the button to scroll to the top of the page.</p>
<button onClick={scrollToTop} style={{ padding: "10px 20px" }}>
Scroll to Top
</button>
<div
style={{
height: "2000px",
background: "linear-gradient(to bottom, #f0f0f0, #d0d0d0)",
}}
>
Scroll down to see the effect
</div>
</div>
)
}| Name | Type | Description | Default Value | Optional |
|---|---|---|---|---|
target | Window or Element | The element to scroll to the top. Defaults to window. | window | Yes |
behavior | ScrollBehavior | The scrolling behavior, either "auto" or "smooth". Defaults to "smooth". | "smooth" | Yes |
| Name | Type | Description |
|---|---|---|
scrollToTop | () => void | Function to scroll the target element to the top. |