Reputation: 213
How do I render nested JSON data on react material UI data grid. In the sandbox attached I want to show the phone numbers of the users from the json on the data grid-Nested JSON Data Grid
Upvotes: 20
Views: 40719
Reputation: 1246
The signature changed a bit in DataGrid v7
.
row
is now the second param.
{
field: 'distributorName',
headerName: 'Distributor',
valueGetter: (_, row) => row.distributor.fullName,
}
Upvotes: 0
Reputation: 321
I use this in my project :
{
field: 'idMaintenancePlan',
headerName: 'Plan de maintenance',
sortable: false, width: 200,
valueGetter: (params) => params.row?.maintenancePlan?.name
}
Upvotes: 32
Reputation: 581
This one worked for me:
const columns = [
{
field: "post",
headerName: "TITLE",
valueFormatter: (post: any) => post.value.title
}
]
In my case post
is a property of the tutorial
entity.
<DataGrid
rows={tutorials}
columns={columns}
slots={{
toolbar: GridToolbar,
}}
/>
The Tutorial
entity
export interface Tutorial {
id: number;
...
post: Post;
}
... and the Post
entity.
export interface Post {
id: number;
title: string;
...
}
Upvotes: 0
Reputation: 69
this works fine also
{
field: "family",
headerName: "Family",
width: 150,
renderCell: (params) => {
return <div className="rowitem">{params.row.family.name}</div>;
},
},
Upvotes: 6
Reputation: 1212
this works fine for me
{ field: 'parserInfo', headerName: 'Parser Title', valueFormatter: ({ value }) => value.title }
Upvotes: 8
Reputation: 878
To solve the problem, let's see params
object passed in valueGetter
function. Log that and you will find a row
object under it. Instead of using params.getValue()
, you should access the row
object. It seems that params.getValue()
can only be used on one-level JSON object. Here is the code snippet to output phone
field.
{
field: "phone",
headerName: "Phone",
width: 160,
valueGetter: (params) => {
console.log({ params });
let result = [];
if (params.row.phone) {
if (params.row.phone.home) {
result.push("home: " + params.row.phone.home);
}
if (params.row.phone.office) {
result.push("office: " + params.row.phone.office);
}
} else {
result = ["Unknown"];
}
return result.join(", ");
}
}
Update
To have more flexibility on checking if every key under a object exists, I have created a helper method:
const checkKeysUnderObject = (obj, result) => {
for (let key in obj) {
if (key) { // push the value to the result array only if key exists
result.push(key + ": " + obj[key]);
}
}
};
usage of the helper method:
if (params.row.phone) {
checkKeysUnderObject(params.row.phone, result);
}else{
result = ["Unknown"];
}
I have also updated the codesandbox here.
Upvotes: 18