跳到主要内容

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.

信息

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>();

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

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

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",
});

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>.

信息

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();

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

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

Above, you can see the pagination properties from dataGridProps.

备注

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

提示

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

const { dataGridProps } = useDataGrid({
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();

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

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

Above, you can see the sorting properties from dataGridProps.

备注

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

提示

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

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

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();

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} columns={columns} 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();

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

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

Above, you can see the filtering properties from dataGridProps.

备注

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

提示

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

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

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();

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} columns={columns} 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

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
rows[]pageSize25
rowCount0onPageSizeChange
disableSelectionOnClicktruesortingMode"server"
loadingfalsesortModel
paginationMode"server"onSortModelChange
page0filterMode"server"
onPageChangefilterModel
onStateChangeonFilterModelChange

警告

The onStateChange callback is used internally by the useDataGrid hook. If you want to override it, you can use like this:

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

return (
<List>
<DataGrid
{...dataGridProps}
columns={columns}
autoHeight
onStateChange={(state) => {
dataGridProps.onStateChange(state);
// do something else
}}
/>
</List>
);
};

Live StackBlitz Example