3.1.1 • Published 2 years ago

react-use-scrollspy v3.1.1

Weekly downloads
1,247
License
MIT
Repository
github
Last release
2 years ago

react-use-scrollspy

Build Status npm version npm GitHub license Donate

Example

Installation

react-use-scrollspy is a React Hook which requires React 16.8.0 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({
  sectionElementRefs: [], // Array of References to DOM elements
});
ParameterDefaultTypeDescription
defaultValue0intDefault value that is returned (optional)
offsetPx0intSet offset (optional)
sectionElementRefs[][Ref]Array of Refs to observe (e.g. via React refs)
scrollingElementwindowRefTarget of the scrolling (e.g. via React refs)) (optional)

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({
    sectionElementRefs: sectionRefs,
    offsetPx: -80,
  });

  return (
    <nav className="App-navigation">
      <span className={activeSection === 0 ? "App-navigation-item App-navigation-item--active" : "App-navigation-item"}>Section 1</span>
      <span className={activeSection === 1 ? "App-navigation-item App-navigation-item--active" : "App-navigation-item"}>Section 2</span>
      <span className={activeSection === 2 ? "App-navigation-item App-navigation-item--active" : "App-navigation-item"}>Section 3</span>
    </nav>

    <section className="App-section" ref={sectionRefs[0]}>
      <h1>Section 1</h1>
    </section>
    <section className="App-section" ref={sectionRefs[1]}>
      <h1>Section 2</h1>
    </section>
    <section className="App-section" ref={sectionRefs[2]}>
      <h1>Section 3</h1>
    </section>
  )
3.1.1

2 years ago

3.1.0

2 years ago

3.0.2

2 years ago

3.0.1

3 years ago

3.0.0

3 years ago

2.0.1

3 years ago

2.0.0

5 years ago

1.1.0

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago