Back to Reui

Scrollspy

content/docs/components/radix/scrollspy.mdx

2.0.03.2 KB
Original Source

<ComponentPreview styleName="radix-nova" name="c-scrollspy-1" className="[&_.preview>[data-orientation=vertical]]:sm:max-w-[80%] **:[.preview]:min-h-[580px]" align="start" />

Installation

<CodeTabs> <TabsList> <TabsTrigger value="cli">CLI</TabsTrigger> <TabsTrigger value="manual">Manual</TabsTrigger> </TabsList> <TabsContent value="cli">
bash
npx shadcn@latest add @reui/scrollspy
</TabsContent> <TabsContent value="manual"> <Steps>

<Step>Copy and paste the following code into your project.</Step>

<ComponentSource styleName="radix-nova" name="scrollspy" title="components/reui/scrollspy.tsx" />

</Steps> </TabsContent> </CodeTabs>

Usage

tsx
import { Scrollspy } from "@/components/reui/scrollspy"
tsx
<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

<ComponentPreview styleName="radix-nova" name="c-scrollspy-2" className="[&_.preview>[data-orientation=vertical]]:sm:max-w-[80%] **:[.preview]:min-h-[530px]" align="start" />

API Reference

Scrollspy

The main component that wraps the navigation links and manages the scroll spying logic.

PropTypeDefaultDescription
targetRefRefObject<HTMLElement | Document>windowThe scrollable container to monitor.
onUpdate(id: string) => void-Callback fired when the active section changes.
offsetnumber0Global pixel offset from the top when calculating active sections.
smoothbooleantrueWhether to use smooth scrolling when clicking on anchors.
historybooleantrueWhether to update the URL hash when the active section changes.
dataAttributestring"scrollspy"The prefix for data attributes (e.g., data-scrollspy-anchor).
classNamestring-Additional CSS classes for the wrapper.

Data Attributes

Navigation links within Scrollspy should use these attributes to connect to sections:

AttributeDescription
data-scrollspy-anchorRequired. The ID of the target section (without the #).
data-scrollspy-offsetOptional. Overrides the global offset for this specific link.

The component adds data-active="true" to the link element when its corresponding section is active.