6
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[React]Hooks を使って無限スクロールを実装する

Posted at

Reactでいろんなサンプルを作って理解しようとしてるんですが、その中で無限スクロールを作ってみたので Memo :pencil:

サンプルは こちら

サンプルの API はこちらの API を使わせてもらいました。
https://punkapi.com/

import React, { FC, useEffect } from 'react';
// setPageNumber でページを変えると fetch してくる hook。取得してきたものは beers にたまっていく
import useBeers from 'hooks/useBeers';
import lodash from 'lodash';

const InfiniteScroll: FC = () => {
  const { beers, setPageNumber } = useBeers();

  // 一番下に到達したら setPageNumber でページを更新
  const handleScroll = lodash.throttle(() => {
    if (
      window.innerHeight + document.documentElement.scrollTop !==
      document.documentElement.offsetHeight
    ) {
      return;
    }
    setPageNumber(prev => prev + 1);
  }, 200);

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <>
      <ul>
        {beers.map((beer: any) => (
          <li key={beer.id}>
            <img src={beer.imageSrc} />
            <div>{beer.title}</div>
          </li>
        ))}
      </ul>
    </>
  );
};

export default InfiniteScroll;
6
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?