What is React Table and how does it work with Hygraph?
React Table is a free, open-source, headless library (part of Tanstack Table) for building tables in React applications. It provides an API for creating tables and performing operations such as sorting, filtering, and pagination. In the Hygraph guide, React Table is used to fetch data from Hygraph's GraphQL API and display it in a tabular format, supporting client-side operations like filtering, sorting, and pagination. For more details, see React Table: A Complete Guide.
What are the key features of the React Table library?
The React Table library offers features such as lightweight size (5kb - 14kb+), headless design (manage state and hooks for all functionalities, use your own UI), full customizability (JSX, templates, state, styles, callbacks), TypeScript support, no data calls (uses passed-in data only), and support for table functionalities like filtering, sorting, and pagination. For more, visit Tanstack Table Documentation.
How can I create and manage tables in a React application using React Table?
React Table provides hooks such as useReactTable to instantiate a table and access methods for creating and managing table data. You define columns and data, use hooks for core row models, and create table markup using HTML tags like table, thead, tbody, tfoot, th, tr, and td. UI frameworks like Chakra UI can be integrated for styling. For a full implementation example, see React Table: A Complete Guide.
What table operations are supported by React Table?
React Table supports filtering, sorting, and pagination. These operations can be implemented using state variables and corresponding hooks provided by the library. For large datasets, server-side operations are recommended, but the guide demonstrates client-side implementations for learning purposes. See the full guide at React Table: A Complete Guide.
How can I reuse the React Table component for different data types?
To make React Table reusable, decouple the data fetching logic and column definitions from the table component. Pass data and columns as props to the ReactTable component, allowing it to display any type of data. Use TypeScript generics to define props for flexibility. For implementation details, see React Table: A Complete Guide.
Features & Capabilities
What features does Hygraph offer?
Hygraph offers a GraphQL-native architecture, content federation, scalability, and a wide range of integrations including hosting (Netlify, Vercel), eCommerce (Shopify, BigCommerce), localization (Lokalise, Crowdin), digital asset management (Cloudinary, AWS S3), personalization (Ninetailed), and AI (AltText.ai). For a full list, visit Hygraph Integrations.
Does Hygraph provide an API?
Yes, Hygraph provides a powerful GraphQL API for efficient content fetching and management. Learn more at Hygraph API Reference.
Where can I find technical documentation for Hygraph?
Comprehensive technical documentation is available at Hygraph Documentation, covering everything needed to build and deploy projects.
Pricing & Plans
What is Hygraph's pricing model?
Hygraph offers a free forever Hobby plan, a Growth plan starting at $199/month, and custom Enterprise plans. For details, visit the Hygraph Pricing Page.
Use Cases & Benefits
Who can benefit from using Hygraph?
Hygraph is ideal for developers, IT decision-makers, content creators, project/program managers, agencies, solution partners, and technology partners. Companies that benefit most include modern software companies, enterprises seeking to modernize, and brands aiming to scale globally or improve development velocity. For more, see Hygraph Product Page.
What business impact can customers expect from using Hygraph?
Customers can expect time-saving through streamlined workflows, ease of use with an intuitive interface, faster speed-to-market, and enhanced customer experience via scalable content delivery. For more, see Hygraph Product Page.
How long does it take to implement Hygraph and how easy is it to start?
Hygraph is designed for easy onboarding, even for non-technical users. For example, Top Villas launched a new project in just 2 months. Users can start quickly by signing up for a free account and using documentation and onboarding guides. See Hygraph Documentation.
Pain Points & Solutions
What problems does Hygraph solve?
Hygraph reduces reliance on developers for content updates, modernizes legacy tech stacks, addresses conflicting needs of global teams, and improves user experience for content creation. Financially, it lowers operational costs, speeds up time-to-market, and supports scalability. Technically, it simplifies development workflows, streamlines query management, and resolves cache and integration challenges. For more, see Hygraph Product Page.
What are the key pain points Hygraph addresses for different personas?
For developers: boilerplate code and overwhelming queries are solved by Hygraph's GraphQL-native platform. For content creators/project managers: the need for developers to update content and clunky user experience are solved by an intuitive interface. For business stakeholders: high operational costs and difficulty to scale are solved by streamlined workflows and scalability. For more, see Hygraph Product Page.
Performance & Technical Requirements
How does Hygraph optimize content delivery performance?
Hygraph emphasizes optimized content delivery performance, ensuring rapid content distribution and responsiveness. This reduces bounce rates and increases conversions, positively impacting user experience and search engine rankings. For more, visit Choosing a Headless CMS.
Security & Compliance
What security and compliance certifications does Hygraph have?
Hygraph is SOC 2 Type 2 compliant, ISO 27001 certified, and GDPR compliant. It offers SSO integrations, audit logs, encryption at rest and in transit, and sandbox environments. For more, visit Hygraph Security Features.
Support & Implementation
What customer service or support is available after purchasing Hygraph?
Hygraph offers 24/7 support via chat, email, and phone. Enterprise customers receive dedicated onboarding and expert guidance. All users have access to documentation, video tutorials, and a community Slack channel. For more, visit Hygraph Contact Page.
What training and technical support is available to help customers get started?
Hygraph provides 24/7 support, onboarding sessions for enterprise customers, training resources (video tutorials, documentation, webinars), and Customer Success Managers for expert guidance. For more, visit Hygraph Contact Page.
Customer Success & Case Studies
Can you share specific case studies or success stories of customers using Hygraph?
Yes. Komax achieved 3X faster time to market, Autoweb saw a 20% increase in website monetization, Samsung improved customer engagement with a scalable platform, and Dr. Oetker enhanced their digital experience using MACH architecture. More stories are available at Hygraph Customer Stories.
What industries are represented in Hygraph's case studies?
Industries include Food and Beverage (Dr. Oetker), Consumer Electronics (Samsung), Automotive (AutoWeb), Healthcare (Vision Healthcare), Travel and Hospitality (HolidayCheck), Media and Publishing, eCommerce, SaaS (Bellhop), Marketplace, Education Technology, and Wellness and Fitness. See Hygraph Case Studies.
Blog & Community
Where can I find the Hygraph blog and what kind of content does it offer?
The Hygraph Blog provides developer tutorials, latest updates, and essential guides to content modeling. Visit Hygraph Blog for news and insights.
Who authored the React Table blog post?
The React Table blog post was written by Aagam Vadecha and Joel Olawanle. Last updated by Aagam on Sep 08, 2024.
How to efficiently use the react-table library to create tables in our React application.
Last updated by Aagam
on Sep 08, 2024
Originally written by Joel
A table is an arrangement that organizes any information into rows and columns—it stores and displays data in a structured and clear format that everyone can understand. For example, when you want to display dashboard statistics, a list of details such as staff details, products, students, and lots more.
Implementing tables in React can get cumbersome and technical, especially when you need to perform basic table functionalities like sorting, filtering, pagination, and lots more.
Tanstack table is a free open-source headless library with around 25K stars on GitHub. It allows you to build tables and has individual libraries to support different frameworks like React, Vue, Angular, Solid, etc.
Tanstack React Table or React Table library is part of the tanstack table that allows us to build tables in React applications. It gives you an API to build tables and do different operations on them, it follows a headless UI approach and allows you to fully build your custom UI. It is also very flexible to use.
React table uses hooks to help build tables, giving you complete control over how you want the UI to appear and function (Headless UI). These hooks are lightweight, fast, fully customizable, and flexible but do not render any markup or styles for you. React Table is used by many well-known tech companies due to its flexibility and easy-to-implement features. These features, such as sorting, pagination, and filtering, are implemented with hooks.
You can check these points to see if you should be using the React Table library
The current UI framework does not provide a Table component
If your current UI framework does not provide a table component and you need to add a table, then you can consider React Table to manage all tables in your application. UI Frameworks like Material-UI or AntD would already have a Table component, in those cases maybe checking if those components fulfill your requirements would make more sense.
Headless Solution
If you want full control over the table's look and feel without being tied to any specific UI or styling framework. React Table’s headless design seamlessly integrates CSS and different UI libraries. Again, if your UI library already has a Table component that works for your use cases, it does not make sense to add extra overhead with an additional library.
Other Considerations
It is highly customizable and provides an extensive API for all table-related operations.
It has strong community support.
It is lightweight, fast, and comes with proper TypeScript support.
It has an intermediate learning curve and will need some time for API exploration and using various features.
In this article, we will fetch some data from Hygraph via GraphQL, and then display that data in a table using the @tanstack/react-table library. Also, we will implement client-side sorting, filtering, and pagination, and finally, we will see how to extend our table component to display any kind of data. In our Hygraph project, we have created a model and populated it with some mock employee data. Hygraph is a headless CMS that enables teams to distribute content to any channel. If this is your first time learning about Hygraph, establish a free-forever developer account.
Base setup
In a situation where you have successfully added all your data to hygraph, or you have your content API ready, we can now fetch these data into our application and store it in a state.
To fetch our data from Hygraph, we use GraphQL using the graphql-request library. We can install this library using the command below in our project directory. Also, we will be using TanStack table’s React library to build our table. We will need to install this library as well.
npm i graphql-request
npm i @tanstack/react-table
Getting data from Hygraph
Once the above installation is done, we can navigate to a fresh component to create our table. We will use useState() to store our data and the useEffect() hook to fetch our data from Hygraph.
Let us declare types for our data first
types.ts
exportinterfaceIEmployee{
id: number,
firstName: string;
lastName: string;
email: string;
department: string;
dateJoined: string;
}
Create a file to store our API requests.
api.ts
importrequestfrom"graphql-request";
import{HYGRAPH_URL}from"./utils/constants";
exportconstgetTableData=async()=>{
const response =awaitrequest(
HYGRAPH_URL,
`{
employees (first:50) {
id_number
firstName
lastName
email
department
dateJoined
}
}`
);
return response;
};
Use the API request in our component to fetch the data
ReactTable.tsx
import{ getTableData }from"../../api.ts";
import{ useState, useEffect }from"react";
import{IEmployee}from"../../utils/types.ts";
exportconstReactTable=()=>{
const[data, setData]= useState<IEmployee[]>([]);
useEffect(()=>{
constfetchData=async()=>{
const{ employees }=awaitgetTableData();
setData(employees);
};
fetchData();
},[]);
return<div>...</div>;
};
Column definition
When using React tables, data and columns are the two significant pieces of information needed. The information we will pass into the rows is known as the data, and the objects used to define the table columns are called the columns (headers, rows, how we will show the row, etc.). We will create columns in a separate file and then import them into our component.
columns.ts
import{ColumnDef}from"@tanstack/react-table";
import{IEmployee}from"../../utils/types";
exportconstCOLUMNS:ColumnDef<IEmployee>[]=[
{
header:"ID",
accessorKey:"id_number",
},
{
header:"First Name",
accessorKey:"firstName",
},
{
header:"Last Name",
accessorKey:"lastName",
},
{
header:"Email",
accessorKey:"email",
},
{
header:"Department",
accessorKey:"department",
},
{
header:"Date Joined",
accessorKey:"dateJoined",
},
];
The columns array consists of objects representing single columns in our table. Currently, we have specified the configuration of these objects with two items:
header: This is the column's header, which will be displayed at the top of each column.
accessorKey: this is the key from our data that will be used to assign value to a column.
There can be more configuration added to this column object, for example, this is how one row of our data coming from Hygraph looks like:
{
id:1,
firstName:"Tandi",
lastName:"Withey",
email:"twithey0@arizona.edu",
department:"Marketing",
dateJoined:"2014-10-23T07:29:35Z",
}
The dateJoined column value like this 2014-10-23T07:29:35Z will look bad and unreadable in the table with all the hour, minute, and second data. We can use the cell property to display the data however we want as shown below:
...
{
header:"Date Joined",
accessorKey:"dateJoined",
cell:(info)=>{
const value =(info.getValue()as string).substring(0,10)
return value
}
}
...
Next, let's say instead of displaying firstName and lastName as two different columns we want to combine data into a single column, we can do it using the accessorFn property as shown below:
These are some basic use cases, for custom requirements you can further explore the column definition API in detail here
The Table instance
React table makes use of hooks in its headless approach. The first hook we will use is the useReactTable hook to instantiate our table so we can access all the methods needed to create our table.
The useReactTable hook requires at least columns, data, and getCoreRowModel to be passed to it as an argument. We should also use the useMemo hook to help memoize our columns array to avoid unnecessary re-renders.
From the table instance table above we can get functions like getHeaderGroups, getRowModel, and getFooterGroups, these functions can be used to form our table markup.
For table markup, we can use HTML tags like table, thead,tbody, tfoot, th, tr, and td. We are using Chakra for this example but feel free to use any UI framework of your choice.
We can use React Table’s API to perform common table-related operations like filtering, pagination, and sorting. Ideally, for very huge datasets these operations happen on the server side. However, for this article and understanding React Table’s API we will demonstrate how to do basic filtering, pagination, and sorting using the React Table API.
Filtering
For filtering the table data first we will need to set up a state variable and capture the user input for filtering the data
We will need to import getFilteredRowModel and pass it in the react table object initialization. Also, we will need to pass our state globalFilter and its function setGlobalFilter while creating the table instance as shown below:
That’s it, now we can use react table’s API and build some basic pagination functionality like going to the previous page, next page, first page, and last page. First, we need to destructure the required utility functions from the table instance as shown below
const{
// ... existing code ...
firstPage,
previousPage,
lastPage,
nextPage,
getCanNextPage,
getCanPreviousPage,
}= table;
firstPage will allow us to navigate to the first page, lastPage will send the user to the last page of the table, getCanPreviousPage will return a boolean value if the user can go to the previous page, previousPage will navigate the user to the previous page, and similarly, getCanNextPage will return a boolean value if the user can go to the next page and nextPage will move current view to the next page.
Finally, we can build the necessary UI at the bottom of the table for the user to navigate.
// ... existing code …
import{
// ... existing code ...
HStack,
IconButton,
Heading,
}from"@chakra-ui/react";
import{
ArrowBackIcon,
ArrowForwardIcon,
ArrowLeftIcon,
ArrowRightIcon,
}from"@chakra-ui/icons";
// ... existing code ...
<HStack align="center" justify="center" m={4}>
<IconButton
icon={<ArrowLeftIcon/>}
onClick={()=>firstPage()}
aria-label=""
>
FirstPage
</IconButton>
<IconButton
icon={<ArrowBackIcon/>}
isDisabled={!getCanPreviousPage()}
onClick={()=>previousPage()}
aria-label=""
>
PrevPage
</IconButton>
<IconButton
icon={<ArrowForwardIcon/>}
isDisabled={!getCanNextPage()}
onClick={()=>nextPage()}
aria-label=""
>
NextPage
</IconButton>
<IconButton
icon={<ArrowRightIcon/>}
onClick={()=>lastPage()}
aria-label=""
>
LastPage
</IconButton>
</HStack>
// ... existing code ...
Below is all the combined code that we will need for implementing table pagination.
import{
// ... existing code ...
getPaginationRowModel,
}from"@tanstack/react-table";
import{
// ... existing code ...
HStack,
IconButton,
Heading,
}from"@chakra-ui/react";
import{
ArrowBackIcon,
ArrowForwardIcon,
ArrowLeftIcon,
ArrowRightIcon,
}from"@chakra-ui/icons";
exportconstReactTable=()=>{
// ... existing code ...
const table =useReactTable({
// ... existing code ...
getPaginationRowModel:getPaginationRowModel(),
});
const{
getHeaderGroups,
getRowModel,
firstPage,
previousPage,
lastPage,
nextPage,
getCanNextPage,
getCanPreviousPage,
}= table;
return(
<TableContainer p={8}>
<Heading>ReactTableExample</Heading>
<Input
value={globalFilter ||""}
onChange={(e)=>setGlobalFilter(e.target.value)}
placeholder="Search all columns..."
my={4}
/>
<Table>
// ... existing code ...
</Table>
<HStack align="center" justify="center" m={4}>
<IconButton
icon={<ArrowLeftIcon/>}
onClick={()=>firstPage()}
aria-label=""
>
FirstPage
</IconButton>
<IconButton
icon={<ArrowBackIcon/>}
isDisabled={!getCanPreviousPage()}
onClick={()=>previousPage()}
aria-label=""
>
PrevPage
</IconButton>
<IconButton
icon={<ArrowForwardIcon/>}
isDisabled={!getCanNextPage()}
onClick={()=>nextPage()}
aria-label=""
>
NextPage
</IconButton>
<IconButton
icon={<ArrowRightIcon/>}
onClick={()=>lastPage()}
aria-label=""
>
LastPage
</IconButton>
</HStack>
</TableContainer>
);
}
Sorting
To add sorting functionality to our table, we will need to create a state variable for storing the sorting state. We will then need to pass the sorting state sorting and its setter function setSorting and getSortedRowModel while creating the table instance.
With the current example, we have displayed employee data, but it cannot be extended further to display product data, or order data, or any other data. To make it reusable, we need to decouple the parts specific to the data i.e. the data and the columns. We should extract the data fetching logic and the columns in a parent component and pass the data and columns as props to our ReactTable component. This way our ReactTable can be repurposed for displaying any type of data.
First, remove data and column-related code from our ReactTable component and create a new EmployeeTable component that will have context around “Employee” related things, and the ReactTable component will not even have the context that it is displaying employees.
In this guide, we have learned how and when to use the React table library in our application. We fetched data on runtime from a HyGraph API and displayed that data in a tabular format using the React Table APIs. We further explored the library and available APIs for utilities like filtering, pagination, and sorting. Finally, we extracted our table component passing it data and column as props, so it can be repurposed for various use cases.
Blog Authors
Aagam Vadecha
Joel Olawanle
Share with others
Sign up for our newsletter!
Be the first to know about releases and industry news and insights.