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
- Node.js https://nodejs.org
Create an initial React project:
npx create-react-app react-datatable cd react-datatable
npm install react-data-table-component
Start React app:
Access http://localhost:3000 on a web browser to see the result:
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).
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