Skip to main content
Refine AI

React Table

refine offers a TanStack Table adapter with @pankod/refine-react-table that allows you to use the TanStack Table library with refine. All features such as sorting, filtering, and pagination come out of the box. Under the hood it uses useList for the fetch. Since it is designed as headless, It expects you to handle the UI.

All of TanStack Table's features are supported and you can use all of the TanStack Table's examples with no changes just copy and paste them into your project.

INFORMATION

useTable hook is extended from useTable hook from the @pankod/refine-core package. This means that you can use all the features of useTable hook.

Installation

Install the @pankod/refine-react-table library.

npm i @pankod/refine-react-table

Basic Usage

In basic usage, useTable returns the data as it comes from the endpoint. By default, it reads resource from the url.

localhost:3000/posts
Live previews only work with the latest documentation.
import React from "react";
import { useTable, ColumnDef, flexRender } from "@pankod/refine-react-table";

interface IPost {
id: number;
title: string;
content: string;
status: "published" | "draft" | "rejected";
}

const PostList: React.FC = () => {
const columns = React.useMemo<ColumnDef<IPost>[]>(
() => [
{
id: "id",
header: "ID",
accessorKey: "id",
},
{
id: "title",
header: "Title",
accessorKey: "title",
},
{
id: "status",
header: "Status",
accessorKey: "status",
},
{
id: "createdAt",
header: "CreatedAt",
accessorKey: "createdAt",
},
],
[],
);

const { getHeaderGroups, getRowModel } = useTable({
columns,
});

return (
<table>
<thead>
{getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<th key={header.id}>
{flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</th>
);
})}
</tr>
))}
</thead>
<tbody>
{getRowModel().rows.map((row) => {
return (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => {
return (
<td key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
);
};

Pagination

TanStack Table provides a bunch of methods that we can use to control the pagination. For example, we can use the setPageSize method to set the current pageSize. Every change in the pageSize and pageIndex will trigger a new request to the data provider.

It also syncs the pagination state with the URL if you enable the syncWithLocation.

INFORMATION

useTable hook from @pankod/refine-react-table sets manualPagination to true by default to handle the pagination. If you set hasPagination to false in refineCoreProps property in the useTable config, it will disable the server-side pagination and it will let you handle the pagination on the client side.

localhost:3000/posts
Live previews only work with the latest documentation.
import React from "react";
import { useTable, ColumnDef, flexRender } from "@pankod/refine-react-table";

interface IPost {
id: number;
title: string;
content: string;
status: "published" | "draft" | "rejected";
}

const PostList: React.FC = () => {
const columns = React.useMemo<ColumnDef<IPost>[]>(
() => [
{
id: "id",
header: "ID",
accessorKey: "id",
},
{
id: "title",
header: "Title",
accessorKey: "title",
},
{
id: "status",
header: "Status",
accessorKey: "status",
},
{
id: "createdAt",
header: "CreatedAt",
accessorKey: "createdAt",
},
],
[],
);

const {
getHeaderGroups,
getRowModel,
getState,
setPageIndex,
getCanPreviousPage,
getPageCount,
getCanNextPage,
nextPage,
previousPage,
setPageSize,
getPrePaginationRowModel,
} = useTable({
columns,
});

return (
<div>
<table>
<thead>
{getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<th key={header.id}>
{header.isPlaceholder ? null : (
<>
{flexRender(
header.column.columnDef
.header,
header.getContext(),
)}
</>
)}
</th>
);
})}
</tr>
))}
</thead>
<tbody>
{getRowModel().rows.map((row) => {
return (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => {
return (
<td key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
{/* Pagination can be built however you'd like. */}
{/* This is just a very basic UI implementation: */}
<div>
<button
onClick={() => setPageIndex(0)}
disabled={!getCanPreviousPage()}
>
{"<<"}
</button>
<button
onClick={() => previousPage()}
disabled={!getCanPreviousPage()}
>
{"<"}
</button>
<button onClick={() => nextPage()} disabled={!getCanNextPage()}>
{">"}
</button>
<button
onClick={() => setPageIndex(getPageCount() - 1)}
disabled={!getCanNextPage()}
>
{">>"}
</button>
<span>
<div>Page</div>
<strong>
{getState().pagination.pageIndex + 1} of{" "}
{getPageCount()}
</strong>
</span>
<span>
| Go to page:
<input
type="number"
defaultValue={getState().pagination.pageIndex + 1}
onChange={(e) => {
const page = e.target.value
? Number(e.target.value) - 1
: 0;
setPageIndex(page);
}}
/>
</span>
<select
value={getState().pagination.pageSize}
onChange={(e) => {
setPageSize(Number(e.target.value));
}}
>
{[10, 20, 30, 40, 50].map((pageSize) => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
</div>
<div>{getPrePaginationRowModel().rows.length} Rows</div>
</div>
);
};

Sorting

TanStack Table provides a bunch of methods that we can use to control the sorting. For example, we can use the setColumnOrder method to set the current sorting value. Every change in the sorting state will trigger a new request to the data provider.

It also syncs the sorting state with the URL if you enable the syncWithLocation.

localhost:3000/posts
Live previews only work with the latest documentation.
import React from "react";
import { useTable, ColumnDef, flexRender } from "@pankod/refine-react-table";

interface IPost {
id: number;
title: string;
content: string;
status: "published" | "draft" | "rejected";
}

const PostList: React.FC = () => {
const columns = React.useMemo<ColumnDef<IPost>[]>(
() => [
{
id: "id",
header: "ID",
accessorKey: "id",
},
{
id: "title",
header: "Title",
accessorKey: "title",
},
{
id: "status",
header: "Status",
accessorKey: "status",
},
{
id: "createdAt",
header: "CreatedAt",
accessorKey: "createdAt",
},
],
[],
);

const { getHeaderGroups, getRowModel } = useTable({
columns,
});

return (
<table>
<thead>
{getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<th key={header.id}>
{header.isPlaceholder ? null : (
<>
<div
onClick={header.column.getToggleSortingHandler()}
>
{flexRender(
header.column.columnDef
.header,
header.getContext(),
)}
{{
asc: " 🔼",
desc: " 🔽",
}[
header.column.getIsSorted() as string
] ?? null}
</div>
</>
)}
</th>
);
})}
</tr>
))}
</thead>
<tbody>
{getRowModel().rows.map((row) => {
return (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => {
return (
<td key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
);
};

Filtering

TanStack Table provides a bunch of methods that we can use to control the filtering. For example, we can use the setColumnFilters method to set the current columnFilters value. Every change in the filter will trigger a new request to the data provider.

It also syncs the filtering state with the URL if you enable the syncWithLocation.

You can specify which field will be filtered with which filter operator with the filterOperator property in the meta object. filterOperator must be a CrudOperators type.

Realtime Updates

This feature is only available if you use a Live Provider.

When the useTable hook is mounted, it will call the subscribe method from the liveProvider with some parameters such as channel, resource etc. It is useful when you want to subscribe to live updates.

Refer to the liveProvider documentation for more information

Properties

TIP

It also accepts all props of TanStack Table.

resource

Default: It reads the resource value from the current URL.

It will be passed to the getList method from the dataProvider as parameter via the useList hook. The parameter is usually used as an API endpoint path. It all depends on how to handle the resource in the getList method. See the creating a data provider section for an example of how resources are handled.

useTable({
resource: "categories",
});

dataProviderName

If there is more than one dataProvider, you should use the dataProviderName that you will use. It is useful when you want to use a different dataProvider for a specific resource.

useTable({
refineCoreProps: {
dataProviderName: "second-data-provider",
},
});

initialCurrent

Default: 1

Sets the initial value of the page index.

useTable({
refineCoreProps: {
initialCurrent: 2, // This will cause the table to initially display the second page, rather than the default of the first page
},
});

initialPageSize

Default: 10

Sets the initial value of the page size.

useTable({
refineCoreProps: {
initialPageSize: 20, // This will cause the table to initially display 20 rows per page, rather than the default of 10
},
});

initialSorter

Sets the initial value of the sorter. The initialSorter is not permanent. It will be cleared when the user changes the sorter. If you want to set a permanent value, use the permanentSorter prop.

useTable({
refineCoreProps: {
initialSorter: [
{
field: "title",
order: "asc",
},
],
},
});

permanentSorter

Sets the permanent value of the sorter. The permanentSorter is permanent and unchangeable. It will not be cleared when the user changes the sorter. If you want to set a temporary value, use the initialSorter prop.

useTable({
refineCoreProps: {
permanentSorter: [
{
field: "title",
order: "asc",
},
],
},
});

initialFilter

Sets the initial value of the filter. The initialFilter is not permanent. It will be cleared when the user changes the filter. If you want to set a permanent value, use the permanentFilter prop.

useTable({
refineCoreProps: {
initialFilter: [
{
field: "title",
operator: "contains",
value: "Foo",
},
],
},
});

permanentFilter

Sets the permanent value of the filter. The permanentFilter is permanent and unchangeable. It will not be cleared when the user changes the filter. If you want to set a temporary value, use the initialFilter prop.

useTable({
refineCoreProps: {
permanentFilter: [
{
field: "title",
operator: "contains",
value: "Foo",
},
],
},
});

defaultSetFilterBehavior

Default: merge

The filtering behavior can be set to either "merge" or "replace".

  • When the filter behavior is set to "merge", it will merge the new filter with the existing filters. This means that if the new filter has the same column as an existing filter, the new filter will replace the existing filter for that column. If the new filter has a different column than the existing filters, it will be added to the existing filters.

  • When the filter behavior is set to "replace", it will replace all existing filters with the new filter. This means that any existing filters will be removed and only the new filter will be applied to the table.

You can also override the default value by using the second parameter of the setFilters function.

useTable({
refineCoreProps: {
defaultSetFilterBehavior: "replace",
},
});

hasPagination

Default: true

Determines whether to use server-side pagination or not.

useTable({
refineCoreProps: {
hasPagination: false,
},
});

syncWithLocation

Default: false

When you use the syncWithLocation feature, the useTable's state (e.g. sort order, filters, pagination) is automatically encoded in the query parameters of the URL, and when the URL changes, the useTable state is automatically updated to match. This makes it easy to share table state across different routes or pages and to allow users to bookmark or share links to specific table views.

Also you can set this value globally on <Refine> component.

useTable({
refineCoreProps: {
syncWithLocation: true,
},
});

queryOptions

useTable uses useList hook to fetch data. You can pass queryOptions.

useTable({
refineCoreProps: {
queryOptions: {
retry: 3,
},
},
});

metaData

metaData is used following two purposes:

  • To pass additional information to data provider methods.
  • Generate GraphQL queries using plain JavaScript Objects (JSON). Please refer GraphQL for more information.

In the following example, we pass the headers property in the metaData object to the create method. With similar logic, you can pass any properties to specifically handle the data provider methods.

useTable({
refineCoreProps: {
metaData: {
headers: { "x-meta-data": "true" },
},
},
});

const myDataProvider = {
//...
getList: async ({
resource,
pagination,
hasPagination,
sort,
filters,
metaData,
}) => {
const headers = metaData?.headers ?? {};
const url = `${apiUrl}/${resource}`;

//...
//...

const { data, headers } = await httpClient.get(`${url}`, { headers });

return {
data,
};
},
//...
};

successNotification

NotificationProvider is required for this prop to work.

After data is fetched successfully, useTable can call open function from NotificationProvider to show a success notification. With this prop, you can customize the success notification.

useTable({
refineCoreProps: {
successNotification: (data, values, resource) => {
return {
message: `${data.title} Successfully fetched.`,
description: "Success with no errors",
type: "success",
};
},
},
});

errorNotification

NotificationProvider is required for this prop to work.

After data fetching is failed, useTable will call open function from NotificationProvider to show an error notification. With this prop, you can customize the error notification.

useTable({
refineCoreProps: {
errorNotification: (data, values, resource) => {
return {
message: `Something went wrong when getting ${data.id}`,
description: "Error",
type: "error",
};
},
},
});

liveMode

LiveProvider is required.

Determines whether to update data automatically ("auto") or not ("manual") if a related live event is received. It can be used to update and show data in Realtime throughout your app. For more information about live mode, please check Live / Realtime page.

useTable({
refineCoreProps: {
liveMode: "auto",
},
});

onLiveEvent

LiveProvider is required.

The callback function is executed when new events from a subscription have arrived.

useTable({
refineCoreProps: {
onLiveEvent: (event) => {
console.log(event);
},
},
});

liveParams

LiveProvider is required.

Params to pass to liveProvider's subscribe method.

Return Values

TIP

It also have all return values of TanStack Table.

refineCore

tableQueryResult

Returned values from useList hook.

sorter

Current sorter state.

setSorter

 (sorter: CrudSorting) => void;

A function to set current sorter state.

filters

Current filters state.

setFilters

((filters: CrudFilters, behavior?: SetFilterBehavior) => void) & ((setter: (prevFilters: CrudFilters) => CrudFilters) => void)

A function to set current filters state.

current

Current page index state. If pagination is disabled, it will be undefined.

setCurrent

React.Dispatch<React.SetStateAction<number>> | undefined;

A function to set the current page index state. If pagination is disabled, it will be undefined.

pageSize

Current page size state. If pagination is disabled, it will be undefined.

setPageSize

React.Dispatch<React.SetStateAction<number>> | undefined;

A function to set the current page size state. If pagination is disabled, it will be undefined.

pageCount

Total page count state. If pagination is disabled, it will be undefined.

createLinkForSyncWithLocation

(params: SyncWithLocationParams) => string;

A function creates accessible links for syncWithLocation. It takes SyncWithLocationParams as parameters.

FAQ

How can I handle relational data?

You can use useMany hook to fetch relational data.

localhost:3000/posts
Live previews only work with the latest documentation.
import React from "react";
import { useTable, ColumnDef, flexRender } from "@pankod/refine-react-table";
import { GetManyResponse, HttpError, useMany } from "@pankod/refine-core";

interface ICategory {
id: number;
title: string;
}

interface IPost {
id: number;
title: string;
content: string;
status: "published" | "draft" | "rejected";
category: {
id: number;
};
}

const PostList: React.FC = () => {
const columns = React.useMemo<ColumnDef<IPost>[]>(
() => [
{
id: "id",
header: "ID",
accessorKey: "id",
},
{
id: "title",
header: "Title",
accessorKey: "title",
},
{
id: "status",
header: "Status",
accessorKey: "status",
},
{
id: "createdAt",
header: "CreatedAt",
accessorKey: "createdAt",
},
{
id: "category",
header: "Category",
accessorKey: "category.id",
cell: function render({ getValue, table }) {
const meta = table.options.meta as {
categoryData: GetManyResponse<ICategory>;
};
// Gets the category from the meta.categoryData object, which is the result of the useMany hook We pass this data to meta with the setOptions function.
const category = meta.categoryData?.data?.find(
(item) => item.id === getValue(),
);

return category?.title ?? "Loading...";
},
},
],
[],
);

const {
getHeaderGroups,
getRowModel,
setOptions,
refineCore: {
tableQueryResult: { data: tableData },
},
} = useTable<IPost, HttpError>({
columns,
});

// Fetches the category of each post. It uses the useMany hook to fetch the category data from the API.
const { data: categoryData } = useMany<ICategory, HttpError>({
resource: "categories",
// Creates the array of ids. This will filter and fetch the category data for the relevant posts.
ids: tableData?.data?.map((item) => item?.category?.id) ?? [],
queryOptions: {
// Set to true only if the posts array is not empty.
enabled: !!tableData?.data,
},
});

// set meta data to table options. We will use this data in cell render.
setOptions((prev) => ({
...prev,
meta: {
...prev.meta,
categoryData,
},
}));

return (
<table>
<thead>
{getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<th key={header.id}>
{flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</th>
);
})}
</tr>
))}
</thead>
<tbody>
{getRowModel().rows.map((row) => {
return (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => {
return (
<td key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
);
};

API Reference

Properties

Type Parameters

PropertyDesriptionTypeDefault
TDataResult data of the query. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError

Return values

PropertyDescriptionType
refineCoreThe return values of the useTable in the coreUseTableReturnValues
Tanstack Table Return ValuesSee TanStack Table documentation

Example

Run on your local
npm create refine-app@latest -- --example table-react-table-basic