React Scroll Agent
Tiny, 6 KB (pre-gzip) scrollspy component that performantly runs at 60 FPS thanks to
requestAnimationFrame
and
@reach/observe-rect.
Install
npm i --save react-scroll-agent @reach/observe-rect
Example
import ScrollAgent from 'react-scroll-agent'; <ScrollAgent = ="section[data-scrollspy]" ="center"> <section ="section-1" > <h1>Section 1</h1> </section> <section ="section-2" > <h1>Section 2</h1> </section> <section ="section-3" > <h1>Section 3</h1> </section></ScrollAgent>;
Props
Name | Type | Required | Default | Description |
---|---|---|---|---|
selector |
String |
✅ | Any CSS selector to specify which elements in children to attach the scrollspy to. |
|
children |
React Node | Standard child passthrough. This is where it watches for scroll events. | ||
detectEnd |
Boolean |
true |
If true , the last index will be highlighted when scrolled to the bottom. If false , then when scrolled to the bottom, current will return whichever container is currently at threshold . |
|
nav |
React Node | Render prop that returns current index in view and all positions of items. |
||
threshold |
String |
"top" |
Trigger point at which current watches. Accepts "top" , "center" , or "bottom" (if a specific threshold is needed, simply add padding to the top or bottom of a container). |
Nav
The nav
render prop returns the following items:
<ScrollAgent =
Name | Type | Description |
---|---|---|
current |
Number |
The index of the current item in view, in visual descending order on the page (may not necessarily be DOM order). |
positions |
[Number] |
An array of all absolute Y values on the page, ordered from top to bottom. Useful for animating scroll to a certain item. |
IIFE & ESM
This module ships with ESM and IIFE versions! To load it just request:
ESM (9 KB unminified)
;