I'm using Material UI V4 Data Grid component in a React Js app.
The Data Grid component has required rows (list type) and columns (list type) props.
Here is a sample of a row item:
const rows = [
{
id: 1,
customerName: "Silvestr Irma",
carModel: {
name: "Centurion",
color: "red"
},
location: {
name: "Belgium",
address: "avenue Verheyen 93"
}
},
];
and here is a sample of the column list:
const columns = [
{
field: "customerName",
headerName: "Custom Name",
flex: 1,
minWidth: 200
},
{
field: "carModel",
headerName: "Car Model",
flex: 1,
minWidth: 200,
renderCell: (params) => (
<Typography variant="subtitle2" className={classes.bolderText}>
{params.value.name}
</Typography>
)
},
{
field: "location",
headerName: "Location",
flex: 1,
minWidth: 300,
renderCell: (params) => (
<div>
<Typography variant="subtitle2" className={classes.bolderText}>
{params.value.name}
</Typography>
<Typography variant="subtitle2" className={classes.ligtherText}>
{params.value.address}
</Typography>
</div>
)
}
];
If we sort the Data Grid component based on the customer name column, the sort works fine for both ascendant and descendant as we can see in the images below:


However, the sort doesn't work fine for columns that have render cell field (car model and location columns) as you can see in the images below:




So how I implement custom sort for columns that have render cell field?
For example the car model name column (Centurion, Centaur, and Buffalo) and the location name column (Belgium, Germany, and Spain).
Here is the full code https://codesandbox.io/s/stackoverflow-custom-sort-data-grid-material-ui-dp609
As you've probably guessed, with the renderCell, you'll need to create a custom function (sortComparator) so the DataGrid knows how to sort the columns. In your case, this sort might suffice:
{
field: "location",
headerName: "Location",
flex: 1,
minWidth: 300,
renderCell: (params) => (
<div>
<Typography variant="subtitle2" className={classes.bolderText}>
{params.value.name}
</Typography>
<Typography variant="subtitle2" className={classes.ligtherText}>
{params.value.address}
</Typography>
</div>
),
sortComparator: (v1, v2) => v1.name.localeCompare(v2.name)
}
Working example: https://codesandbox.io/s/stackoverflow-custom-sort-data-grid-material-ui-forked-2kw12?file=/src/App.jsx:416-1248
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With