React-Use-Scrollspy

Flexible React Hook to automatically update navigation based on scroll position

⚠️ Heads up: React Hooks are not part of a stable React release yet. ⚠️

Example

Installation

react-use-scrollyspy is a React Hook which requires React 16.7.0-alpha or later.

// yarn
yarn add react-use-scrollspy
// or npm
npm i react-use-scrollspy --S

Usage

import useScrollSpy from 'react-use-scrollspy';
...
const activeSection = useScrollSpy({
  sectionElements: [], // Array of DOM elements
});
Parameter Default Type Description
defaultValue 0 int Default value that is returned (optional)
offsetPx 0 int Set offset (optional)
sectionElements [] [(DOM) Element] Array of DOM elements to observe (e.g. via React refs)

with Refs

Use React refs for section elements like in the provided example.

import React, { useRef } from 'react';
import useScrollSpy from 'react-use-scrollspy';

const App = () => {

  const sectionRefs = [
    useRef(null),
    useRef(null),
    useRef(null),
  ];

  const activeSection = useScrollSpy({
    sectionElements: sectionRefs.map(ref => ref.current),
    offsetPx: -80,
  });

  return (

Subscribe to the Newsletter

Get our latest news,tutorials,guides,tips & deals delivered to your inbox.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

shares