Powered By GE-COMPONENTS From YY GFE TEAM
It provided useSmoothScroll
hook for finishing smooth scroll behaviour in react component, and useScrollWatch
to return some information in scroll container.
It 's a more convenient way to replace native scrollTo
api.
Storybook Docs are Here.
requsetAnimationFrame
api to finish smooth scroll behaviour.direction
option ,you can set x
for horizontal, y
for vertical.npm install react-smooth-scroll-hook
import React, { useRef } from 'react';
import useSmoothScroll from 'react-smooth-scroll-hook';
export const Demo = () => {
// A custom scroll container
const ref = useRef(null);
// Also support document.body / document.documentElement, and you don't need to set a ref passing to jsx
const ref = useRef(document.body);
const { scrollTo } = useSmoothScroll({
ref,
speed: 100,
direction: 'y',
});
return (
<>
<button onClick={() => scrollTo('#item-20')}>scrollTo('#item-20')</button>
<div
// if use custom scroll container, pass ref
ref={ref}
style={{
overflowY: 'scroll',
maxHeight: '200px',
}}
>
{Array(100)
.fill(null)
.map((_item, i) => (
<div key={i} id={`item-${i}`}>
item-{i}
</div>
))}
</div>
</>
);
};
RefObject<HTMLElement>
, container which set as overflow: scroll
, if scroll whole document, pass ref = useRef(document.documentElement)
or useRef(document.body)
.requestAnimationFrame
mode, defaults to 100
, if not provide, speed depends on native API scrollTo
.x
for horizontal or y
for vertical.1
, unit of px
.scrollTo (string|number) => void
number
: the distance to scroll, e.g. scrollTo(400)
string
: the element seletor you want to scrollTo, meanwhile passing to document.querySelector
, e.g. scrollTo('#your-dom-id')
reachedTop boolean
: Whether it has reached the top of refContainer
reachedBottom boolean
: Whether it has reached the bottom of refContainer
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
.
import React, { useRef } from 'react';
import { useScrollWatch } from 'react-smooth-scroll-hook';
export const ScrollConatainerMode = () => {
const ref = useRef(null);
const { scrollTop, curIndex, curItem } = useScrollWatch({
ref,
list: [
{
href: '#item-0',
},
{
href: '#item-10',
},
{
href: '#item-20',
},
],
});
return (
<>
<h2>Scroll Container Mode</h2>
<div>
<p>
<strong>scrollTop:</strong> {scrollTop}
</p>
<p>
<strong>curIndex:</strong> {curIndex}
</p>
<p>
<strong>curHref:</strong> {curItem?.href}
</p>
</div>
<div
style={{
padding: '10px',
maxHeight: '200px',
overflowY: 'scroll',
}}
ref={ref}
>
{Array(100)
.fill(null)
.map((_item, i) => (
<div key={i} id={`item-${i}`}>
item-{i}
</div>
))}
</div>
</>
);
};
Array({href, offset})
: href
is elemet selector string, which passing to querySelector
, such as #element-id
useSmoothScroll
number
: current scrollTop of scroll container.number
: current Index of list{href, offset}
: current Item of list#react #reacthoook #hook #javascript