DEV Community

Cover image for How to paginated data in ant design table
Jahidul Islam (Saeid)
Jahidul Islam (Saeid)

Posted on

How to paginated data in ant design table

In Ant Design, you can use the pagination attribute of the Table component to paginate data.

And onChange (callback function that gets called when the page number or page size changes).

Here is an example of how to use the pagination attribute in a Table component:

import { Table } from "antd";
import { useState, useEffect } from "react";
import axios from "axios";

function App() {
  const [dataSource, setDataSource] = useState([]);
  const [totalPassengers, setTotalPassengers] = useState(1);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchRecords(1, 10);
  }, []);
  const columns = [
    {
      title: "ID",
      dataIndex: "_id",
      key: "_id",
    },
    {
      title: "Name",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "Trips",
      dataIndex: "trips",
      key: "trips",
    },
  ];

  const fetchRecords = (page, pageSize) => {
    setLoading(true);
    axios
      .get(`https://api.instantwebtools.net/v1/passenger?page=${page}&size=${pageSize}`)
      .then((res) => {
        setDataSource(res.data.data);
        setTotalPassengers(res.data.totalPassengers);
        setLoading(false);
      });
  };

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <Table
        loading={loading}
        columns={columns}
        dataSource={dataSource}
        pagination={{
          total: totalPassengers,
          onChange: (page, pageSize) => {
            fetchRecords(page, pageSize);
          },
        }}
        bordered
      ></Table>
    </div>
  );
}
export default App;

Enter fullscreen mode Exit fullscreen mode

You can also use the pagination.total to set the total number of records

Codesandbox Example : https://codesandbox.io/s/tender-khorana-6oww0d

Top comments (0)