Passing an Image in Material-UI Data-Grid Table

Viewed 4951

there. I would like to add an image in a material-ui data-grid table. But it's not working. What am I missing here? I tried to search the docs but couldn't see any example that used images.

My code

import { DataGrid } from '@material-ui/data-grid';


const columns = [

  {
    field: 'image',
    headerName: 'Image',
    width: 150,
    editable: true,
  },
  {
    field: 'name',
    headerName: 'Name',
    width: 150,
    editable: true,
  },
  

];

const rows = [
  {
    id: 1,
    image: "image URL",
    type: 'image',
    name: 'Cheese Burger',
    price: 10_000,
    menu: 'Daily Menu',
    category: 'Burgers'
  },
  {
    id: 2,
    image: "image URL",
    name: 'Diet Coke',
    price: 10_000,
    menu: 'Daily Menu',
    category: 'Driks'
  },

];

export const ItemsTable = () => {
  return (
    <div style={{ height: 300, width: '100%' }} className="mt-7">
      <DataGrid
        rows={rows}
        columns={columns}
        pageSize={5}
        checkboxSelection
        disableSelectionOnClick
      />
    </div>
  );
}

Desired result enter image description here

What's I'm getting enter image description here

1 Answers

The renderCell prop allows you to inject components into the DataGrid, creating a column of custom cells.

https://smartdevpreneur.com/add-buttons-links-and-other-custom-cells-in-material-ui-datagrid/#How_to_Add_Other_Custom_Components

Material-Ui's documentation on renderCell.

https://mui.com/components/data-grid/columns/#render-cell

Just need to pass in the value into the image component src.

I made a codesandbox to show renderCell in action.

https://codesandbox.io/s/rendercellgrid-material-demo-edq5p?file=/demo.js

const columns = [

  {
    field: 'image',
    headerName: 'Image',
    width: 150,
    editable: true,
    renderCell: (params) => <img src={params.value} />, // renderCell will render the component
  },
  {
    field: 'name',
    headerName: 'Name',
    width: 150,
    editable: true,
  },
  

];
Related