Scrollspy
Tracks the user’s scroll position on the page and automatically highlights the corresponding link in the table of contents.
6.8 KB
•Updated on August 21, 2026
Installation
Bash
pnpm dlx shadcn@latest add @spaceui/components-spaceui-scrollspyUsage
Code
import { Scrollspy } from '@/components/spaceui/scrollspy'Code
<Scrollspy targetRef={containerRef}>
<a href="#section-1" data-scrollspy-anchor="section-1">Section 1</a>
<a href="#section-2" data-scrollspy-anchor="section-2">Section 2</a>
</Scrollspy>
<div ref={containerRef}>
<div id="section-1">Content 1</div>
<div id="section-2">Content 2</div>
</div>Examples
Horizontal
API Reference
Scrollspy
The main component that wraps the navigation links and manages the scroll spying logic.
| Prop | Type | Default | Description |
|---|---|---|---|
targetRef | RefObject<HTMLElement|Document> | window | The scrollable container to monitor. |
onUpdate | (id: string) => void | - | Callback fired when the active section changes. |
offset | number | 0 | Global pixel offset from the top when calculating active sections. |
smooth | boolean | true | Whether to use smooth scrolling when clicking on anchors. |
history | boolean | true | Whether to update the URL hash when the active section changes. |
dataAttribute | string | scrollspy | The prefix for data attributes (e.g., data-scrollspy-anchor). |
className | string | - | Additional CSS classes for the wrapper. |
Data Attributes
Navigation links within Scrollspy should use these attributes to connect to sections:
| Attribute | Description |
|---|---|
data-scrollspy-anchor | Required. The ID of the target section (without the #). |
data-scrollspy-offset | Optional. Overrides the global offset for this specific link. |
The component adds data-active="true" to the link element when its corresponding section is active.
Keep in mind
- MIT License: Free and open-source for personal and commercial use. Feel free to copy, tweak, and adapt the components to match your exact needs.
- Credits & Inspiration: Some components on this site are inspired by or recreated from great ideas across the web. I'm not here to take credit; just to learn, experiment, and push interface craft further.
- Reach out & Claims: If an attribution was missed, or if you have any inquiry or claim, feel free to reach out directly on X to @adrielzimbril. I'll be glad to update or resolve it right away.