https://github.com/Purii/react-use-scrollspy
Flexible React Hook to automatically update navigation based on scroll position
https://github.com/Purii/react-use-scrollspy
hooks hooks-api-react javascript react reactjs scrollspy
Last synced: 22 days ago
JSON representation
Flexible React Hook to automatically update navigation based on scroll position
- Host: GitHub
- URL: https://github.com/Purii/react-use-scrollspy
- Owner: Purii
- License: mit
- Created: 2018-11-18T12:33:58.000Z (over 6 years ago)
- Default Branch: main
- Last Pushed: 2024-08-15T17:45:17.000Z (8 months ago)
- Last Synced: 2025-03-21T22:03:23.221Z (24 days ago)
- Topics: hooks, hooks-api-react, javascript, react, reactjs, scrollspy
- Language: TypeScript
- Homepage: https://purii.github.io/react-use-scrollspy/
- Size: 3.32 MB
- Stars: 319
- Watchers: 4
- Forks: 18
- Open Issues: 16
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
- fucking-awesome-react-hooks - `useScrollSpy`
- awesome-react-hooks-cn - `useScrollSpy`
- awesome-react-hooks - `useScrollSpy`
- awesome-react-hooks - `useScrollSpy`
README
# react-use-scrollspy
[](https://travis-ci.org/Purii/react-use-scrollspy)
[](https://www.npmjs.com/package/react-use-scrollspy)
[](https://www.npmjs.com/package/react-use-scrollspy)
[](https://raw.githubusercontent.com/Purii/react-use-scrollspy/master/LICENSE)
[](https://www.patreon.com/purii)
## Installation
`react-use-scrollspy` is a React `Hook` which requires React **16.8.0 or later.**
```sh
// yarn
yarn add react-use-scrollspy
// or npm
npm i react-use-scrollspy --S
```## Usage
```javascript
import useScrollSpy from 'react-use-scrollspy';
...
const activeSection = useScrollSpy({
sectionElementRefs: [], // Array of References to DOM elements
});
```| Parameter | Default | Type | Description |
| :----------------- | :------: | :-----: | ----------------------------------------------------------- |
| defaultValue | `0` | `int` | Default value that is returned (optional) |
| offsetPx | `0` | `int` | Set offset (optional) |
| sectionElementRefs | `[]` | `[Ref]` | Array of Refs to observe (e.g. via React `refs`) |
| scrollingElement | `window` | `Ref` | Target of the scrolling (e.g. via React `refs`)) (optional) |### with Refs
Use React `refs` for section elements like in the [provided example](/example).
```javascript
import React, { useRef } from 'react';
import useScrollSpy from 'react-use-scrollspy';const App = () => {
const sectionRefs = [
useRef(null),
useRef(null),
useRef(null),
];const activeSection = useScrollSpy({
sectionElementRefs: sectionRefs,
offsetPx: -80,
});return (
Section 1
Section 2
Section 3
Section 1
Section 2
Section 3
)
```