I see some data structure problems in your code and components not used.
First one being avatars, can be set using MUI components, such as.. <Avatar>
Avatar Component MUI
Which can be added through:
<Avatar alt="Remy Sharp" src="/static/images/avatar/1.jpg" />
But to use it, you've of course to import it, so, other than the DataGrid
, you import also the Avatar
component:
import Avatar from '@mui/material/Avatar';
By giving an interpretation to what you're doing about the rows, there's a problem. Because you are trying to render into the column user
the values of: username
and avatar
. To achieve that, you need to have them both on that. I took a Datagrid
fiddle, pasted your code and made some fix, in a way you can see what I mean.
Here is the fiddle: DataGrid Text + Avatar column example
And here's the code in the fiddle also revised a little bit.
import React from "react";
import { DataGrid } from "@mui/x-data-grid";
import Avatar from "@mui/material/Avatar";
export default function UserList() {
const columns = [
{ field: "id", headerName: "ID", width: 70 },
{
field: "user",
headerName: "User",
width: 200,
renderCell: (params) => {
console.log(params);
return (
<>
<Avatar src={params.value.avatar} />
{params.value.username}
</>
);
}
},
{ field: "email", headerName: "E-mail", width: 130 },
{
field: "status",
headerName: "Status",
width: 90
},
{
field: "transaction",
headerName: "Transaction",
width: 100
}
];
const rows = [
{
id: 1,
user: {
username: "Harry Potter",
avatar:
"https://assets.materialup.com/uploads/bebad102-7f40-4941-99cd-54366113003e/avatar-08.png"
},
email: "Harry@gmail.com",
status: "Active",
transaction: "$120"
}
];
return (
<>
<DataGrid
autoHeight
rows={rows}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
checkboxSelection
/>
</>
);
}
As you can see, it's very important the part that you defined, 5 columns in the columns
variable:
- id
- user
- email
- status
- transaction
Whilst the values provided in rows, included 6 rows. This was the first problem. Restructure the code to accomodate the column structure the DataGrid
component is expecting to receive.
So instead of:
{ id: 1,
username: 'Harry Potter', avatar:"https://assets.materialup.com/uploads/bebad102-7f40-4941-99cd-54366113003e/avatar-08.png",
email:"Harry@gmail.com",
status:"Active",
transaction:"$120"
}
Using the column name user
to keep the data of either the username
and the avatar
together. To access such data in the params
, you should go through params.value
, which allows direct access to the column values, instead of going through params.row, which gives you access to the whole row, but you should do something like params.row.user.username
and params.row.user.avatar
. It's longer, and I'd use it only if I want to join some existing columns to put together a new one with concatenated values. Otherwise I think it's easier to use params.value
.