I'm creating a MUI web application to track some personal data.
I'm using MUI datagrid pro to display data and as we know it has some pretty extensive filters inside its datagrid component.
I want to display the sum of the currently displayed filtered columns without having to re-query the database to get these specific values. It feels like it should be fairly simple, but I don't know how to access it.
datagridpro API is located at: https://mui.com/x/api/data-grid/data-grid-pro/
My data grid component is constructed as follows:
const fetchData = useCallback( async (IDs: string[]) => { response = await fetch("/api/data") data = response.json() ... ... ... transformedData = transformData(data) return { data: transformedData }, }; [dispatch] );
This is provided via the standard useEffect to set state using data.
The transformedData method is similar to:
const transformedData = (data: any) => { return data.map((item: any, index: any) => { const timestamp = new Date(item.timestamp) return { id: item.id value_1: item.value_1 value_2: item.value_2 date: timestamp value_3: item.value_3 }; }); };
This is the current code that displays the DataGridPro component:
<DataGridPro rows={transformedDataFromFunction} sx={{ ".MuiDataGrid-row:hover": { backgroundColor: "#C2C2C2", }, }} columns={columns} editMode="row" rowModesModel={rowModesModel} onRowModesModelChange={(newModel: typeof rowModesModel) => setRowModesModel(newModel) } onRowEditStart={handleRowEditStart} onRowEditStop={handleRowEditStop} processRowUpdate={processRowUpdate} componentsProps={{ toolbar: { setRowModesModel }, }} slots={{ toolbar: GridToolbar }} // leaving this in here on off chance we don't need MUI // experimentalFeatures={{ newEditingApi: true }} />
Again, I essentially want to display the sum of the specified column in a separate div at the top of the page, formatted like this:
Total value 1: sum(value_1) |Total value 2: sum(value_2) |Total value: sum(index)
[Insert table data here]
Similarly, when I filter based on the MUI data grid, I want to show the sum of these display columns.
Assume value_1 has 4 rows in total and the values are shown below
value_1 | 3 | 4 | 1 | 2
Suppose I want to filter by the value >2
.
On the datagridpro component this will be filtered and displayed as:
value_1 | 3 | 4
I want to display the count
of the displayed column which is 2
and the sum of the rows will be 7
.
What API property should I use to access it?
Thanks
You can use
gridFilteredSortedRowIdsSelector
in theMUI DataGridPro API
to get the sum of columns. This selector returns an array of row IDs currently filtered and sorted in the grid. You can use this array to access the row data and calculate the sum of the required columns. For example, you can do the following:Then
You can view the entire example here: codesandbox.io
To learn more, see Filter Selectors, API Objects and Access Status.