React Table Series - Table of Contents
Part 1 : React Table - How to create a simple react table with pagination and sorting - [This article]
Everyone wants the data at somepoint to be shown in the form of a table. Let us look at how to create a simple table in react with pagination and sorting the data.
To save time, we will use the app that we created before to retrieve data from an API. We will use this data to show in our table. If you want to know how to retrieve data from an API in react, read this tutorial - React Proxy Backend API configuration
Go to the
Download Source
section of the above tutorial and once you get access to the source, follow the below steps, as we will be modifying some of the files in that app.Open command prompt, navigate to the application root folder and type,
npm install react-table
That is all !! Yes, we dont need any other packages.
Now, open Dashboard.js and modify the code as below. This component will just fetches the data and displays as a table.
loading...
Let's review what we did above, here are the things that we added:
1. First we imported the react-table component, a CSS file
2. Default table properties
ReactTableDefaults
are imported and declared. For now, we just have a single property which just disabled the multi sort option, we will come to this later in sorting section3. Added a method to
fetchData()
. This uses the same method getUsers()
to fetch the data from the API from original source of the app4. Additionally, the
fetchData()
calls getTableDataFromJSONObject()
which just converts the data fetched from API into a format that react-table uses5. Finally, added
ReactTable
componentloading...
The method above simply returns 3 attributes:
1.
rows
- the table data in the form of rows2.
pages
- the number of pages in the table3.
totalRecords
- total records in the tableloading...
Finally, you should see the table displayed as below,
You dont have to worry about the pagination as long as you are returning your data in the above format (3 attributes explained above). React Table will take care of the rest.
Sorting is taken care by React Table by default. It will pass the current sort column name in
sorted
property in fetchData()
This sorted property is actually an object that has the sort order as well in desc
property. Once you receive this property, sort your table data accordingly and send back.Check the
defaultSorted
property of ReactTable
component for the default sorted column configurationBy defult, react-table supports multi column sort, Use SHIFT + click on column to select multiple columns. Try this out and see. Most of the times, we dont need this functionality. This is the exact reason why we have to disabled multi column sort in
ReactTableDefaults
.Thats all folks !! Happy coding. If you feel this helped you, keep supporting us by or or below or on the articles on social media.