Skip to main content

Anchor

In-page anchor navigation with scroll-synced highlighting. Driven by the items data (with children support), consuming pure logic from @lh-ui/share/core/anchor.

Basic usage​

Basic usage (click an anchor or scroll to see it follow)
Section 1
Section 2
Section 2.1
Section 3

Active: (none)

Click an anchor or scroll the page to watch the highlight follow.

import { LhAnchor } from '@lh-ui/react'

export default function Demo() {
const items = [
{ id: 'sec-1', title: 'Section 1' },
{ id: 'sec-2', title: 'Section 2', children: [{ id: 'sec-2-1', title: 'Section 2.1' }] },
{ id: 'sec-3', title: 'Section 3' },
]

return <LhAnchor items={items} offset={8} />
}

direction="horizontal" switches to horizontal layout; target listens on a specific scroll container (viewport by default); smooth disables smooth scrolling; offset compensates for the anchor region's offset from the top of the scroll container.

Anchor Props​

PropDescriptionTypeOptionsDefault
itemsAnchor data (children supported)LhAnchorItem[]——
targetScroll container (selector or element, viewport by default)string | HTMLElement——
offsetAnchor region offset from the top of the scroll container (used for sync)number—0
directionLayout directionstring'vertical' | 'horizontal''vertical'
smoothSmooth scrollingboolean—true
sxShorthand layout propsSxProps——

LhAnchorItem​

FieldDescriptionType
idTarget element idstring
titleDisplay textstring
childrenChild anchorsLhAnchorItem[]

Anchor events​

EventDescriptionSignatureVue counterpart
onChangeFires when the active anchor changes (scroll sync or click)(id: string) => void@change
onLinkClickFires when an anchor link is clicked (before the scroll jump)(event, id: string) => void@click
Vue counterpart

items / target / offset / direction / smooth / sx share names and semantics with the LhAnchor of lh-ui-plus; plus's @change maps to onChange, and @click (anchor link click) maps to onLinkClick — the component root is a <nav>, and a link click is semantically different from a whole-block click, so the onClick name is not reused.

Accessibility

The container is a semantic <nav aria-label> (locale pack anchor.label); the active anchor is marked with aria-current="location"; links are real <a href="#id"> anchors (they still navigate without JS, and clicks are enhanced into smooth scrolling); smooth scrolling degrades to an instant jump under prefers-reduced-motion: reduce.

Target elements must exist

Sync is measured via each anchor target's getBoundingClientRect().top; items whose id does not exist in the document are skipped and excluded from syncing. Render target elements on the same page as the anchor.

Styles​

import '@lh-ui/react/theme.css'
import '@lh-ui/react/style/anchor'