Loading...
Please waitLoading...
Please waitpnpm dlx uselab@latest add use-anchor-scroll
import { useAnchorScroll } from "@/hooks/use-anchor-scroll"
function Navigation() {
const { scrollToId } = useAnchorScroll()
return (
<nav>
<button onClick={() => scrollToId("about")}>About</button>
<button onClick={() => scrollToId("contact")}>Contact</button>
</nav>
)
}The hook provides a simple way to scroll to elements by their ID without modifying the URL, making it perfect for single-page applications where you want smooth scrolling navigation without hash changes.
useAnchorScroll()Returns an object with one method:
| Name | Type | Description |
|---|---|---|
scrollToId | (id: string) => void | Scrolls smoothly to the element with the given ID |
scrollToId(id: string)id (required): The ID of the element to scroll to. The element must exist in the DOM and have the matching id attribute.import { useAnchorScroll } from "@/hooks/use-anchor-scroll"
function TableOfContents() {
const { scrollToId } = useAnchorScroll()
return (
<ul>
<li>
<button onClick={() => scrollToId("introduction")}>Introduction</button>
</li>
<li>
<button onClick={() => scrollToId("features")}>Features</button>
</li>
<li>
<button onClick={() => scrollToId("conclusion")}>Conclusion</button>
</li>
</ul>
)
}import { useAnchorScroll } from "@/hooks/use-anchor-scroll"
function SafeNavigation() {
const { scrollToId } = useAnchorScroll()
const handleScroll = (id: string) => {
const element = document.getElementById(id)
if (element) {
scrollToId(id)
} else {
console.warn(`Element with id "${id}" not found`)
}
}
return (
<button onClick={() => handleScroll("section-1")}>Go to Section 1</button>
)
}scrollIntoView with behavior: "smooth" for smooth scrolling animations<a href="#id">)window before executing)Notice how the URL doesn't change when you scroll to a section.
This is the first section. Click the button above to scroll here smoothly without changing the URL.
This is the second section. The scroll animation is smooth and the URL remains unchanged.
This is the third section. Perfect for navigation menus where you want smooth scrolling without URL hash changes.
scrollToId(id) with the element ID you want to scroll toscrollIntoView with smooth behaviorid attribute