Search code examples
material-uidatagrid

How to properly render a button or icon inside Data Grid column?


I have a data grid with a column that holds actions (edit and delete).

Here is my whole code:

import React, { useEffect } from 'react'
import { DataGrid } from '@mui/x-data-grid'
import { useNavigate } from 'react-router-dom'
import EditIcon from '@mui/icons-material/Edit'
import DeleteForeverIcon from '@mui/icons-material/DeleteForever'
import { Button } from '@mui/material'

const rows = [
  {
    id: 1,
    lastName: 'Snow',
    firstName: 'Jon',
    age: 35,
    edit: EditIcon,
    delete: `${(<Button variant="text">Text</Button>)}`,
  },
]

const Colors = () => {

  const columns = [
    { field: 'id', headerName: 'ID', width: 70 },
    { field: 'firstName', headerName: 'First name', width: 130 },
    { field: 'lastName', headerName: 'Last name', width: 130 },
    {
      field: 'age',
      headerName: 'Age',
      type: 'number',
      width: 90,
    },
    { field: 'edit', headerName: 'Edit', width: 150 },
    { field: 'delete', headerName: 'Delete', width: 150 },
  ]

  return (
    <div style={{ height: 560, width: '100%' }}>
      <DataGrid
        sx={{ backgroundColor: 'white' }}
        rows={rows}
        columns={columns}
        pageSize={8}
        rowsPerPageOptions={[8]}
        checkboxSelection
      />
    </div>
  )
}

export default Colors

Now my problem is: I would like to use a material icon inside the edit column.

I tried by implementing icon directly like this:

const rows = [
  {
    id: 1,
    lastName: 'Snow',
    firstName: 'Jon',
    age: 35,
    edit: EditIcon, //<--
  },
]

Or calling a button by this way:

const rows = [
  {
    id: 1,
    lastName: 'Snow',
    firstName: 'Jon',
    age: 35,
    delete: `${(<Button variant="text">Text</Button>)}`,   //<--
  },
]

Result: I'm getting a render [object object] instead of icon or button:

enter image description here

How to properly render a button or icon inside a datagrid column?


Solution

  • I fixed my problem by using renderCell, with this i can render html inside grid data the way i want (i can put button for exemple):

    {
       field: 'edit',
       headerName: 'Edit',
       width: 70,
       renderCell: (params) => {
         return <EditIcon />    //<-- Mui icons should be put this way here.
       },
    },