use-scroll-spy
Track scroll position and detect which heading is currently in the viewport, can be used for table of contents
Source
Docs
Package
Usage
use-scroll-spy hook tracks scroll position and returns index of the
element that is currently in the viewport. It is useful for creating
table of contents components (like in mantine.dev sidebar on the right side)
and similar features.
Scroll to heading:
Hook options
use-scroll-spy accepts an object with options:
selector- selector to get headings, by default it is'h1, h2, h3, h4, h5, h6'getDepth- a function to retrieve depth of heading, by default depth is calculated based on tag namegetValue- a function to retrieve heading value, by defaultelement.textContentis used
Example of using custom options to get headings with data-heading attribute:
Scroll to heading:
Reinitializing hook data
By default, use-scroll-spy does not track changes in the DOM. If you want
to update headings data after the parent component has mounted, you can use
reinitialize function:
Definition
All types used in the definition are exported from @mantine/hooks package.