Thought leadership from the most innovative tech companies, all in one place.

Let's Create a Pagination Data Table with React and an External API

A guide on how to create a pagination data table with React using react-data-table-component

image

In this tutorial, we will demonstrate how to create a pagination data table with React using react-data-table-component and an external API from MeCallAPI.com.

MeCallAPI.com

MeCallAPI.com

You can try to call an API by simply request it from the URL: https://www.mecallapi.com/api/attractions?page=1&per_page=10

Software Installation

Let's begin!

Create an initial React project:

npx create-react-app react-datatable
cd react-datatable

Install react-data-table-component:

npm install react-data-table-component

Start React app:

npm start

Access http://localhost:3000 on a web browser to see the result:

http://localhost:3000

http://localhost:3000

Edit App.js

Let's me explain a bit about the Code:

  • columns (line 4–36) is an array defined as a column for the data table.

  • Define State (line 42) items and a function setItems for setting a value to items. We will call an API and store the response data in items.

  • Define States (line 43 and 44) totalRows to store number of rows/data from the API and perPage to store the number of rows showing per page.

  • Define the function useEffect (line 46–48) as Effect Hook to be called when the component is loaded. We also include perPage as an dependency for React Hook useEffect to be called when perPage value is changed. In our case, the function fetchData will be called.

  • Define the function fetchData (line 50–64) to call the API, for example: https://www.mecallapi.com/api/attractions?page=1&per_page=10 to retrieve a list of attractions stored in items State in React.

  • Define the function handlePageChange (line 66–68) to be executed when the page changed in data table.

  • Define the function handlePerRowsChange (line 70–72) to be executed when the number of rows per page changed in datatable.

  • The component DataTable is rendered in line 80–89 with options to enable remote pagination (paginationServer).

The result:

Pagination datatable

Pagination datatable

Conclusion

That's it. Hope it helps you understand the basics of React and how to use data table with an API. See you next article!

Article by Karn Yongsiriwit, Ph.D. College of Digital Innovation Technology, Rangsit University




Continue Learning