|
| 1 | +import * as React from 'react'; |
| 2 | +import { |
| 3 | + DataGridPremium, |
| 4 | + useKeepGroupedColumnsHidden, |
| 5 | + useGridApiRef, |
| 6 | +} from '@mui/x-data-grid-premium'; |
| 7 | +import { useMockServer } from '@mui/x-data-grid-generator'; |
| 8 | + |
| 9 | +const aggregationFunctions = { |
| 10 | + sum: { columnTypes: ['number'] }, |
| 11 | + avg: { columnTypes: ['number'] }, |
| 12 | + min: { columnTypes: ['number', 'date', 'dateTime'] }, |
| 13 | + max: { columnTypes: ['number', 'date', 'dateTime'] }, |
| 14 | + size: {}, |
| 15 | +}; |
| 16 | + |
| 17 | +export default function ServerSideDataGridAggregationRowGrouping() { |
| 18 | + const apiRef = useGridApiRef(); |
| 19 | + const { |
| 20 | + columns, |
| 21 | + initialState: initState, |
| 22 | + fetchRows, |
| 23 | + } = useMockServer({ rowGrouping: true }); |
| 24 | + |
| 25 | + const dataSource = React.useMemo( |
| 26 | + () => ({ |
| 27 | + getRows: async (params) => { |
| 28 | + const urlParams = new URLSearchParams({ |
| 29 | + paginationModel: JSON.stringify(params.paginationModel), |
| 30 | + filterModel: JSON.stringify(params.filterModel), |
| 31 | + sortModel: JSON.stringify(params.sortModel), |
| 32 | + groupKeys: JSON.stringify(params.groupKeys), |
| 33 | + groupFields: JSON.stringify(params.groupFields), |
| 34 | + aggregationModel: JSON.stringify(params.aggregationModel), |
| 35 | + }); |
| 36 | + const getRowsResponse = await fetchRows( |
| 37 | + `https://mui.com/x/api/data-grid?${urlParams.toString()}`, |
| 38 | + ); |
| 39 | + return { |
| 40 | + rows: getRowsResponse.rows, |
| 41 | + rowCount: getRowsResponse.rowCount, |
| 42 | + aggregateRow: getRowsResponse.aggregateRow, |
| 43 | + }; |
| 44 | + }, |
| 45 | + getGroupKey: (row) => row.group, |
| 46 | + getChildrenCount: (row) => row.descendantCount, |
| 47 | + getAggregatedValue: (row, field) => row[`${field}Aggregate`], |
| 48 | + }), |
| 49 | + [fetchRows], |
| 50 | + ); |
| 51 | + |
| 52 | + const initialState = useKeepGroupedColumnsHidden({ |
| 53 | + apiRef, |
| 54 | + initialState: { |
| 55 | + ...initState, |
| 56 | + rowGrouping: { |
| 57 | + model: ['company', 'director'], |
| 58 | + }, |
| 59 | + aggregation: { |
| 60 | + model: { title: 'size', gross: 'sum', year: 'max' }, |
| 61 | + }, |
| 62 | + }, |
| 63 | + }); |
| 64 | + |
| 65 | + return ( |
| 66 | + <div style={{ width: '100%', height: 400 }}> |
| 67 | + <DataGridPremium |
| 68 | + apiRef={apiRef} |
| 69 | + columns={columns} |
| 70 | + unstable_dataSource={dataSource} |
| 71 | + initialState={initialState} |
| 72 | + aggregationFunctions={aggregationFunctions} |
| 73 | + /> |
| 74 | + </div> |
| 75 | + ); |
| 76 | +} |
0 commit comments