To update a total value stored in React state when a cell is edited in MUI X Data Grid, you need to:
Use the processRowUpdate prop to handle edits
Update your state with the new total
Solution Code
import { DataGrid } from '@mui/x-data-grid';
import { useState, useCallback } from 'react';
function EditableDataGrid() {
const [rows, setRows] = useState([
{ id: 1, name: 'Item 1', price: 10 },
{ id: 2, name: 'Item 2', price: 20 },
{ id: 3, name: 'Item 3', price: 30 },
]);
const [total, setTotal] = useState(60);
const calculateTotal = useCallback((rows) => {
return rows.reduce((sum, row) => sum + row.price, 0);
}, []);
const processRowUpdate = useCallback((newRow, oldRow) => {
const updatedRows = rows.map(row =>
row.id === newRow.id ? newRow : row
);
const newTotal = calculateTotal(updatedRows);
setRows(updatedRows);
setTotal(newTotal);
return newRow;
}, [rows, calculateTotal]);
const columns = [
{ field: 'name', headerName: 'Name', width: 150 },
{
field: 'price',
headerName: 'Price',
width: 150,
type: 'number',
editable: true,
},
];
return (
<div>
<div style={{ height: 400, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
processRowUpdate={processRowUpdate}
experimentalFeatures={{ newEditingApi: true }}
/>
</div>
<div style={{ marginTop: 20 }}>
<strong>Total:</strong> {total}
</div>
</div>
);
}