1.0.0 • Published 3 years ago
react-scrollspy-21 v1.0.0
React Scrollspy Component
react-scrollspy-2020 is a React Component, that automatically update navigation components based on scroll position to indicate which link is currently active in the viewport. It also scrolls (animated) to viewport when click on a navigation component.
Demo with example code
How to install
Install via NPM package manager
npm i react-scrollspy-2021
Install via Yarn package manager
yarn add react-scrollspy-2021
About the Component
- It work as a real react component with
Refs
- It works with nested components (standard
forwardRef
components) - It work on window scrolling (scrollable boxes not supported yet)
- It work with vertical and horizontal scrolling also
How to use it
- Add unique
id
to content blocks.
<App>
<Navigation />
<Section id="box-1">Content here</Section>
<Section id="box-2">Content here</Section>
<Section id="box-3">Content here</Section>
</App>
- Add
ScrollSpy
component to your navigation. You need to addref={createRef()}
to each navigation item that you want to works with ScrollSpy.
import ScrollSpy from 'react-scroll-spy-2021';
// Last item won't use as ScrollSpy item, but you can place there
<ScrollSpy>
<a href="#box-1" ref={createRef()}>
...
</a>
<a href="#box-2" ref={createRef()}>
...
</a>
<a href="#box-3" ref={createRef()}>
...
</a>
<a href="/home">...</a>
</ScrollSpy>
- You can use nested components, but wrapper component(s) need to use
forwardRefs
.
// FancyButton component
const FancyButton = forwardRef(({ href, text }, ref) => (
<a ref={ref} href={href} className="FancyButton">
{text}
</a>
));
// ScrollSpy initialization
<ScrollSpy>
<FancyButton link="#box-1" text="Box 1" ref={createRef()} />
<FancyButton link="#box-2" text="Box 2" ref={createRef()} />
<FancyButton link="#box-3" text="Box 3" ref={createRef()} />
</ScrollSpy>
Configuration
Available ScrollSpy
component properties
className
- class name of active item (default:active
)offsetTop
- if you are usingfixed
orsticky
navigation bar, the vertical scroll position can be adjusting when you click on the navigation item. Value can beinteger
(positive
,negative
orzero
). (default:0
, unit:px
)offsetLeft
- if you are usingfixed
orsticky
navigation bar, the horizontal scroll position can be adjusting when you click on the navigation item. Value can beinteger
(positive
,negative
orzero
). (default:0
, unit:px
)duration
- the scroll animation duration, when you click on a navigation item (default:1000
, unit:ms
)
Sponsorship
I will happy if you can donate/sponsor me via PayPal.Me. Donate Me
License
MIT License. Copyright (c) 2021 Zsolt Tovis
1.0.0
3 years ago