Being a React newbie I have first created a test project with MUI Table, which works well enough:
However I would like to have pagination and sortable columns, when displaying my data.
So I have created another test project using MUI X DataGrid:
As you can see it kind of works, but the last column displays my HTML img code verbatim.
I have tried to use value getter for that in my custom TopGrid.jsx component:
const wrongImgHandler = (photo) => {
return photo && PHOTO_PATTERN.test(photo) ? photo : "female_sad.png";
};
const imgErrorHandler = ({ currentTarget }) => {
// prevents looping
currentTarget.onerror = null;
currentTarget.src = "male_sad.png";
};
const columns = [
{
field: "elo",
headerName: "Elo",
type: "number",
width: 90,
},
{
field: "given",
headerName: "First name",
width: 150,
},
{
field: "photo",
headerName: "Photo",
sortable: false,
width: 160,
valueGetter: (params) =>
`<img
src=${wrongImgHandler(params.row.photo)}
className="avatar"
onError=${imgErrorHandler}
/>`,
},
];
Please advise me, how to display an img element with onError handler in a MUI X DataGrid.
Thank you @super, the renderCell has worked for me:
function Avatar({ photo }) {
const wrongImgHandler = (photo) => {
return photo && PHOTO_PATTERN.test(photo) ? photo : "female_sad.png";
};
const imgErrorHandler = ({ currentTarget }) => {
// prevents looping
currentTarget.onerror = null;
currentTarget.src = "male_sad.png";
};
return (
<img
src={wrongImgHandler(photo)}
className="avatar"
onError={imgErrorHandler}
/>
);
}
Avatar.propTypes = {
photo: PropTypes.string.isRequired,
};
const columns = [
{
field: "elo",
headerName: "Elo",
type: "number",
},
{
field: "given",
headerName: "First name",
width: 200,
},
{
field: "photo",
headerName: "Photo",
align: "center",
sortable: false,
renderCell: (params) => <Avatar photo={params.row.photo} />,
},
];