12
8

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.

Next.js + Ant Designでページネーションできるテーブルを実装する方法

Posted at

この投稿では、Next.jsとAnt Designでページネーションできるテーブルを実装する方法を説明します。使用する言語はTypeScriptです。

できあがりの様子は次の動画のようになります:

ページネーションのUIをクリックすると、データがロードされたり、URLのpageパラメータを直接指定してアクセスした場合に、該当ページが表示されたりするようにします。

このチュートリアルは下記の続きです。

このチュートリアルで作ったものの完成形コードはGitHubにあります

完成形のデモアプリはVercelにホスティングしてあるので、実際に操作してみたい方はそちらをご覧ください。

Next.js + Ant Designでページネーションできるテーブルを実装する方法

Ant Designの<Table>コンポーネントを用います。

いきなり完成形ですが、pages/users.tsxの中身は次のようにします。

pages/users.tsx
import { Avatar, PaginationProps, Table } from "antd";
import { TablePaginationConfig } from "antd/es/table/interface";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";

const { Column } = Table;

export default function Users() {
  const router = useRouter();
  const [data, setData] = useState<ReadonlyArray<any>>([]);
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState<PaginationProps>();

  // URLのpageクエリーパラメータをもとに、APIから所定のページを取ってくるようにします。
  // pageパラメータが変化するごとに発動します。
  useEffect(
    () => fetchUsers((router.query.page as any) ?? 0),
    [router.query.page]
  );

  // これは、ページネーションのUIをクリックしたときに発動します。
  function handleChange({ current = 0 }: TablePaginationConfig) {
    router.push({ pathname: router.pathname, query: { page: current } });
  }

  // ユーザーのダミーデータを提供してくれるAPI、ReqResからデータをお借りします。
  function fetchUsers(page: number = 1) {
    setLoading(true);
    fetch(`https://reqres.in/api/users?page=${page}`)
      .then((res) => res.json())
      .then((data) => {
        setData(data.data);
        setPagination({
          total: data.total,
          pageSize: data.per_page,
          current: data.page,
        });
        setLoading(false);
      });
  }

  return (
    <Table
      rowKey="id"
      dataSource={data}
      loading={loading}
      pagination={pagination}
      onChange={handleChange}
    >
      <Column title="ID" dataIndex="id" />
      <Column
        title="Photo"
        dataIndex="avatar"
        render={(x) => <Avatar src={x} />}
      />
      <Column title="First Name" dataIndex="first_name" />
      <Column title="Last Name" dataIndex="last_name" />
      <Column title="Email" dataIndex="email" />
    </Table>
  );
}

これを実装すると冒頭の動画のように、ページネーションのUIを操作したときにデータがロードされたり、URLにpageパラメータを指定して直接アクセスしたときに該当のページが表示されるようになります。

12
8
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
12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?