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:
[
{
"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.
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,
syncWithLocationwill 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
| Property | Desription | Type | Default |
|---|---|---|---|
| TData | Result data of the query. Extends BaseRecord | BaseRecord | BaseRecord |
| TError | Custom error object that extends HttpError | HttpError | HttpError |
| TSearchVariables | Values for search params | {} |
Return values
| Property | Description | Type |
|---|---|---|
| dataGridProps | MUI X <DataGrid> props | DataGridPropsType* |
| tableQueryResult | Result of the react-query's useQuery | QueryObserverResult<{ data: TData[]; total: number; }, TError> |
| search | It sends the parameters it receives to its onSearch function | (value: TSearchVariables) => Promise<void> |
| current | Current page index state (returns undefined if pagination is disabled) | number | undefined |
| totalPage | Total page count (returns undefined if pagination is disabled) | number | undefined |
| setCurrent | A function that changes the current (returns undefined if pagination is disabled) | React.Dispatch<React.SetStateAction<number>> | undefined |
| pageSize | Current pageSize state (returns undefined if pagination is disabled) | number | undefined |
| setPageSize | A function that changes the pageSize (returns undefined if pagination is disabled) | React.Dispatch<React.SetStateAction<number>> | undefined |
| hideFooterPagination | Whether to hide the footer pagination or not. This value is only returned if hasPagination is set to false | boolean |
| sorter | Current sorting state | CrudSorting |
| setSorter | A function that accepts a new sorter state | (sorter: CrudSorting) => void |
| filters | Current filters state | CrudFilters |
| setFilters | A function that accepts a new filter state | (filters: CrudFilters) => void |
| createLinkForSyncWithLocation | A function create accessible links for syncWithLocation | (params: SyncWithLocationParams) => string; |
DataGridProps
Property Default Property Default rows []pageSize 25rowCount 0onPageSizeChange disableSelectionOnClick truesortingMode "server"loading falsesortModel paginationMode "server"onSortModelChange page 0filterMode "server"onPageChange filterModel onStateChange onFilterModelChange
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>
);
};