This is a hook to control your scrollbar in react component!
Basically; useSmoothScroll hook use requestAnimationFrame to finish smooth scroll behaviour!
If you want to control the speed of scroll behaviour, it defaults to use requestAnimationFrame mode.
Examples are Here.(Storybook)
Live demo is Here.(Codesandbox)
-
🚀 You don't need to warn about compatibility, it use
requsetAnimationFrameapi to finish smooth scroll behaviour. -
👉 Provide
directionoption ,you can setxfor vertical,yfor horizontal. -
💧 No Third Party dependencies, light and pure.
npm install react-smooth-scroll-hookimport React, { useRef } from 'react'; import useSmoothScroll from 'react-smooth-scroll-hook'; export const Demo = () => { const ref = useRef<HTMLDivElement>(null); const { scrollTo } = useSmoothScroll({ ref, }); return ( <> <button onClick={() => scrollTo('#item-20')}>scrollTo('#item-20')</button> <div ref={ref} style={{ overflowY: 'scroll', maxHeight: '200px', }} > <div> {Array(100) .fill(null) .map((_item, i) => ( <div key={i} id={`item-${i}`}> y-{i} </div> ))} </div> </div> </> ); };- ref:
RefObject<HTMLElement>, container which set asoverflow: scroll. - speed: Distance in one frame to move in
requestAnimationFramemode, defaults to100, if not provide, speed depends on native APIscrollTo. - direction: Scroll direction
- threshold: Judge scroll is finished has an error range, .defaults to
1.
-
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
-
reachTop
boolean: Whether it has reached the top of scrollContainer -
reachBottom
boolean: Whether it has reached the bottom of scrollContainer -
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 ofreachTopandreachBottom, just an API as you need, and possibly useful in some situation. -
refreshSize
() => void: Manually refresh the size of ref container, just an API as you need, and possibly useful in some situation.