Skip to main content
Version: 3.xx.xx

useDataGrid

By using useDataGrid, you are able to get properties that are compatible with MUI X <DataGrid> component. All features such as sorting, filtering and pagination comes as out of box. For all the other features, you can refer to the MUI X <DataGrid> documentation.

info

The useDataGrid hook works in compatible with both the <DataGrid> and the <DataGridPro> component.

This hook is extended from useTable from the @pankod/refine-core package.

Basic usage

Let's assume that the data we are going to show on the table came like this from the endpoint:

https://api.fake-rest.refine.dev/posts
[
{
"id": 1,
"title": "A aspernatur rerum molestiae.",
"content": "Natus molestias incidunt voluptatibus. Libero delectus facilis...",
"status": "published"
},
{
"id": 2,
"title": "A molestiae vel voluptatem enim.",
"content": "Voluptas consequatur quia beatae. Ipsa est qui culpa deleniti...",
"status": "draft"
}
]

To see basic usage, let's create a table with the id, title and content columns.

/src/pages/posts/list.tsx
import React from "react";
import { useDataGrid, DataGrid, GridColumns, List } from "@pankod/refine-mui";

const columns: GridColumns = [
{
field: "id",
headerName: "ID",
type: "number",
},
{ field: "title", headerName: "Title" },
{ field: "status", headerName: "Status" },
];

export const PostsList: React.FC = () => {
const { dataGridProps } = useDataGrid<IPost>({
columns,
});

return (
<List>
<DataGrid {...dataGridProps} autoHeight />
</List>
);
};

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

Within the <Refine> component, a resource page knows which resource name it has by reading from the URL.

If you want to use a different resource name, you can pass resource as a prop like this:

const { dataGridProps } = useDataGrid({
resource: "categories",
columns,
});

If the resource option is given, syncWithLocation will not work.

Pagination

The hook handles pagination by setting the paginationMode, page, onPageChange, pageSize and onPageSizeChange props that are compatible with <DataGrid>.

info

To disable pagination, you can set hasPagination property to false which is true by default. If pagination is disabled, hideFooterPagination property will be send as true with paginationMode, page, onPageChange, pageSize and onPageSizeChange set to undefined.

export const PostsList: React.FC = () => {
const { dataGridProps } = useDataGrid({
columns,
});

const {
paginationMode,
page,
onPageChange,
pageSize,
onPageSizeChange,
...restDataGridProps
} = dataGridProps;

return (
<List>
<DataGrid
{...restDataGridProps}
paginationMode={paginationMode}
page={page}
onPageChange={onPageChange}
pageSize={pageSize}
onPageSizeChange={onPageSizeChange}
autoHeight
/>
</List>
);
};

Above, you can see the pagination properties from dataGridProps.

note

To see how the pagination works, you can look at the source code of the useDataGrid hook.

tip

You can set initial values for the pagination by passing initialCurrent and initialPageSize props.

const { dataGridProps } = useDataGrid({
columns,
initialCurrent: 2,
initialPageSize: 10,
});

Sorting

The hook handles sorting by setting the sortingMode, sortModel and onSortModelChangeprops that are compatible with <DataGrid>.

export const PostsList: React.FC = () => {
const { dataGridProps } = useDataGrid({
columns,
});

const { sortingMode, sortModel, onSortModelChange, ...restDataGridProps } =
dataGridProps;

return (
<List>
<DataGrid
{...restDataGridProps}
sortingMode={sortingMode}
sortModel={sortModel}
onSortModelChange={onSortModelChange}
autoHeight
/>
</List>
);
};

Above, you can see the sorting properties from dataGridProps.

note

To see how the sorting works, you can look at the source code of the useDataGrid hook.

tip

You can pass initialSorter prop to set initial sorting and permanentSorter prop to set permanent sorting.

const { dataGridProps } = useDataGrid({
columns,
initialSorter: [{ field: "id", order: "desc" }],
permanentSorter: [{ field: "title", order: "asc" }],
});
tip

If you want to sort externally from the <DataGrid> component. You can use setSorter like this:

import {
useDataGrid,
DataGrid,
GridColumns,
List,
Button,
ButtonGroup,
} from "@pankod/refine-mui";

const columns: GridColumns = [
{
field: "id",
headerName: "ID",
type: "number",
},
{ field: "title", headerName: "Title" },
{ field: "status", headerName: "Status" },
];

export const PostsList: React.FC = () => {
const { dataGridProps, setSorter } = useDataGrid({
columns,
});

const handleSorting = (order: "asc" | "desc") => {
setSorter([
{
field: "title",
order,
},
]);
};

return (
<List>
<ButtonGroup variant="outlined">
<Button onClick={() => handleSorting("asc")}>Asc</Button>
<Button onClick={() => handleSorting("desc")}>Desc</Button>
</ButtonGroup>
<DataGrid {...dataGridProps} autoHeight />
</List>
);
};

Mui X community version only sorts the rows according to one criterion at a time. To use multi-sorting, you need to upgrade to the Pro plan.

However, multiple sorting can be done as server-side without specifying the sortModel.

return <DataGrid {...dataGridProps} sortModel={undefined} autoHeight />;

When sortModel is not passed, it supports more than one criteria at a time, but cannot show which fields are sorted in <DataGrid> headers.

Filtering

The hook handles filtering by setting the filterMode, filterModel and onFilterModelChangeprops that are compatible with <DataGrid>.

export const PostsList: React.FC = () => {
const { dataGridProps } = useDataGrid({
columns,
});

const {
filterMode,
filterModel,
onFilterModelChange,
...restDataGridProps
} = dataGridProps;

return (
<List>
<DataGrid
{...restDataGridProps}
filterMode={filterMode}
filterModel={filterModel}
onFilterModelChange={onFilterModelChange}
autoHeight
/>
</List>
);
};

Above, you can see the filtering properties from dataGridProps.

note

To see how the filtering works, you can look at the source code of the useDataGrid hook.

tip

You can pass initialFilter prop to set initial filter and permanentFilter prop to set permanent filter.

const { dataGridProps } = useDataGrid({
columns,
initialFilter: [{ field: "title", value: "lorem", operator: "contains" }],
permanentFilter: [{ field: "status", value: "draft", operator: "eq" }],
});
tip

If you want to filter externally from the <DataGrid> component. You can use setFilter like this:

import {
useDataGrid,
DataGrid,
GridColumns,
List,
FormControlLabel,
Checkbox,
} from "@pankod/refine-mui";

const columns: GridColumns = [
{
field: "id",
headerName: "ID",
type: "number",
},
{ field: "title", headerName: "Title" },
{ field: "status", headerName: "Status" },
];

export const PostsList: React.FC = () => {
const { dataGridProps, setFilters } = useDataGrid({
columns,
});

const handleFilter = (
e: React.ChangeEvent<HTMLInputElement>,
checked: boolean,
) => {
setFilters([
{
field: "status",
value: checked ? "draft" : undefined,
operator: "eq",
},
]);
};

return (
<List>
<FormControlLabel
label="Filter by Draft Status"
control={<Checkbox onChange={handleFilter} />}
/>
<DataGrid {...dataGridProps} autoHeight />
</List>
);
};

Mui X community version only filter the rows according to one criterion at a time. To use multi-filtering, you need to upgrade to the Pro plan.

However, multiple filtering can be done as server-side without specifying the filterModel.

return <DataGrid {...dataGridProps} filterModel={undefined} autoHeight />;

When filterModel is not passed, it supports more than one criteria at a time, but cannot show which fields are filtered in <DataGrid> headers.

API

Properties

KeyDescriptionTypeDefault
columns
Required
Set of columns of type GridColumnsGridColDef
resourceThe resource to use for table datastring | undefinedResource name that it reads from the URL
permanentFilterDefault and unchangeable filterCrudFilters[]
permanentSorterDefault and unchangeable sorter stateCrudSorting[]
hasPaginationWhether to use server side pagination or notbooleantrue
initialCurrentInitial page indexnumber1
initialPageSizeNumber of records shown per initial number of pagesnumber25
initialSorterInitial sortingCrudSorting
initialFilterInitial filteringCrudFilters
syncWithLocationSortings, filters, page index and records shown per page are tracked by browser historybooleanValue set in Refine. If a custom resource is given, it will be false
onSearchWhen the search form is submitted, it creates the 'CrudFilters' object. Refer to search form to learn how to create a search formFunction
queryOptionsreact-query's useQuery options UseQueryOptions<
{ data: TData[]; },
TError>
metaDataMetadata query for dataProviderMetaDataQuery{}
liveModeWhether to update data automatically ("auto") or not ("manual") if a related live event is received. The "off" value is used to avoid creating a subscription."auto" | "manual" | "off""off"
liveParamsParams to pass to liveProvider's subscribe method if liveMode is enabled{ ids?: string[]; [key: string]: any; }undefined
onLiveEventCallback to handle all related live events of this hook(event: LiveEvent) => voidundefined

Type Parameters

PropertyDesriptionTypeDefault
TDataResult data of the query. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError
TSearchVariablesValues for search params{}

Return values

PropertyDescriptionType
dataGridPropsMUI X <DataGrid> propsDataGridPropsType*
tableQueryResultResult of the react-query's useQueryQueryObserverResult<{
data: TData[];
total: number; },
TError>
searchIt sends the parameters it receives to its onSearch function(value: TSearchVariables) => Promise<void>
currentCurrent page index state (returns undefined if pagination is disabled)number | undefined
totalPageTotal page count (returns undefined if pagination is disabled)number | undefined
setCurrentA function that changes the current (returns undefined if pagination is disabled)React.Dispatch<React.SetStateAction<number>> | undefined
pageSizeCurrent pageSize state (returns undefined if pagination is disabled)number | undefined
setPageSizeA function that changes the pageSize (returns undefined if pagination is disabled)React.Dispatch<React.SetStateAction<number>> | undefined
hideFooterPaginationWhether to hide the footer pagination or not. This value is only returned if hasPagination is set to falseboolean
sorterCurrent sorting stateCrudSorting
setSorterA function that accepts a new sorter state(sorter: CrudSorting) => void
filtersCurrent filters stateCrudFilters
setFiltersA function that accepts a new filter state(filters: CrudFilters) => void
createLinkForSyncWithLocationA function create accessible links for syncWithLocation(params: SyncWithLocationParams) => string;

DataGridProps

PropertyDefaultPropertyDefault
columnspageSize25
rows[]onPageSizeChange
rowCount0sortingMode"server"
disableSelectionOnClicktruesortModel
loadingfalseonSortModelChange
paginationMode"server"filterMode"server"
page0filterModel
onPageChangeonFilterModelChange

Live StackBlitz Example