Flexible React Hook to automatically update navigation based on scroll position
npm install react-use-scrollspy




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
`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) |0
| offsetPx | | int | Set offset (optional) |[]
| sectionElementRefs | | [Ref] | Array of Refs to observe (e.g. via React refs) |window
| scrollingElement | | Ref | Target of the scrolling (e.g. via React refs)) (optional) |
Use React refs for section elements like in the provided 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
)
``