Skip to content

iamyoki/infinite-scroll-hook

 
 

Repository files navigation

🧻 infinite-scroll-hook (React)

🧪 Run Tests 🚀 Release The Package transition hook


Scroll down to load more never been so easy!


example


See Example in Codesandbox



Installation

Install with yarn

yarn add infinite-scroll-hook

Or install with npm

npm install infinite-scroll-hook --save

Usage

Simple usage

export default function App() {
  const [list, setList] = useState([...Array(11).keys()])
  const { containerRef, isLoading } = useInfiniteScroll({
    async onLoadMore() {
      const res = await fetchList(list.slice(-1)[0])
      setList(list.concat(res))
    },
  })

  return (
    <div className="App">
      <List ref={containerRef}>
        {list.map((n) => (
          <Item key={n}>{n}</Item>
        ))}
        {isLoading && <Loading>Loading ...</Loading>}
      </List>
    </div>
  )

Offset

Will load more while scrolling hit to bottom offset '200px'

const { containerRef, isLoading } = useInfiniteScroll({offset: '200px'})
...

All css size units available

  • offset: 200px
  • offset: 20%
  • offset: 20vh
  • offset: 20cm
  • ...

Stop load more

Stops when finished

const { containerRef, isLoading } = useInfiniteScroll({shouldStop: isFetchEnd})
...

return (
    <div className="App">
      <List ref={containerRef}>
        {list.map((n) => (
          <Item key={n}>{n}</Item>
        ))}
        {(isLoading || !isFetchEnd) && <Loading>Loading ...</Loading>}
      </List>
    </div>
  )

API Reference

  const {containerRef, isLoading} = useTransition(options)
Parameters Type Description
options { offset?: string; shouldStop?: boolean; onLoadMore?: () => Promise<void> } This is the option object

Returns Type Description
containerRef LegacyRef<HTMLElement> The ref object attach to your jsx container element
isLoading boolean Whether is loading or not

Also see these amazing hooks

Repo Intro
☄️ transition-hook An extremely light-weight react transition animation hook
🧻 infinite-scroll-hook Scroll down to load more never been so easy!

License

MIT

Languages

  • JavaScript 53.7%
  • TypeScript 43.1%
  • Shell 3.2%