3
1

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 1 year has passed since last update.

Reactで無限スクロールを実現する

Last updated at Posted at 2023-10-25

はじめに

表題通り、Reactで無限スクロールを実現するための仕様です。
そもそも取得件数が多い場合、ページネーションを行います。次にページ遷移する場合、次のページを押して表示する方法が一般的です。無限スクロールはページを押すのでなく、下にスクロールすると次のページ内容を取得する。これが取得の限界までできることから無限スクロールと呼ばれています。(infinitescrollとも呼ばれているようです。)
スクリーンショット 2023-10-25 21.04.08.png

Reactで実装

スクリーンショット 2023-10-25 21.08.25.png

App.tsx
import React, { useState, useEffect } from "react";
import InfiniteScroll from "react-infinite-scroll-component";
import { getJsonPlaceholder } from "./api"

const style = {
  border: "1px solid green",
  padding: 8,
  overflow: "hidden"
};

function App() {
  const [items, setItems] = useState<any[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const newItems = await getJsonPlaceholder(page)
      console.log('page',page)
      setItems(prevItems => [...prevItems, ...newItems]);
      if (newItems.length < 5) {
        setHasMore(false);
      }
      setPage(prevPage => prevPage + 1);
    } catch (error) {
      console.error("Error fetching data: ", error);
      setHasMore(false);
    }
  };

  const fetchMoreData = () => {
    fetchData();
  };

  return (
    <div>
      <h1>JSONPlaceholder Infinite Scroll Example</h1>
      <hr />
      <InfiniteScroll
        dataLength={items.length}
        next={fetchMoreData}
        hasMore={hasMore}
        loader={<h4>Loading...</h4>}
      >
        {items.map((item, index) => (
          <div style={style} key={item.id}>
            <h3>{item.title}</h3>
            <p>{item.body}</p>
          </div>
        ))}
      </InfiniteScroll>
    </div>
  );
}

export default App;

api.ts
import axios from "axios"

export const getJsonPlaceholder = async (page:number) => {
    const response = await axios.get(`https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=5`);
    return response.data;
}
3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?