react-smooth-scroll-hook
The useSmoothScroll
hook finish smooth scroll behaviour in react component by requestAnimationFrame
.
Storybook Docs are Here.
Feature
-
🚀 You don't need to warn about compatibility, it use
requsetAnimationFrame
api to finish smooth scroll behaviour. -
👉 Provide
direction
option ,you can setx
for horizontal,y
for vertical. -
💧 No Third Party dependencies, light and pure.
Installation
npm install react-smooth-scroll-hook
useSmoothScroll
Quick Start
;;;
Props
- ref:
RefObject<HTMLElement>
, container which set asoverflow: scroll
, if scroll whole document, passref = useRef(document.documentElement)
oruseRef(document.body)
. - speed: Distance in one frame to move in
requestAnimationFrame
mode, defaults to100
, if not provide, speed depends on native APIscrollTo
. - direction: Scroll direction,
x
for horizontal ory
for vertical. - threshold: Judge scroll is finished has an error range, .defaults to
1
.
Returns of Hook
-
scrollTo
(string|number) => void
- Pass
number
: the distance to scroll, e.g.scrollTo(400)
- Pass
string
: the element seletor you want to scrollTo, meanwhile passing todocument.querySelector
, e.g.scrollTo('#your-dom-id')
- Pass
-
reachedTop
boolean
: Whether it has reached the top of refContainer -
reachedBottom
boolean
: Whether it has reached the bottom of refContainer -
scrollToPage
(number) => void
: Pass page(number
), which scroll to a distance as multiples of container size(offsetWidth
/offsetHeight
) .e.gscrollToPage(1)
,scrollToPage(-1)
-
refreshState
() => void
: Manually refresh the state ofreachTop
andreachBottom
, possibly useful in some situation. -
refreshSize
() => void
: Manually refresh the size of ref container, possibly useful in some situation.
Demo
useScrollWatch
Proviede a list
of dom like below, and pass the parent container ref
to hook, it return the scrollbar current state of scrollTop
, curIndex
, curItem
.
Quick Start
;;
Props
- list
Array({href, offset})
:href
is elemet selector string, which passing toquerySelector
, such as#element-id
- ref: the same as ref of
useSmoothScroll
Returns of Hook
- scrollTop
number
: current scrollTop of scroll container. - curIndex
number
: current Index of list - curItem
{href, offset}
: current Item of list