MUI data grid boolean cell type conditional formatting - material-ui

Is there a way to conditionally format MUI datagrid cell that has a 'boolean' type.
Here is a sandbox from documentation with a checkbox column that has a boolean type: https://codesandbox.io/s/1ckfjp?file=/demo.tsx:1771-1855
const columns: GridColumns = [
...
{
field: 'isPaid',
headerName: 'Is paid?',
type: 'boolean',
width: 140,
editable: true,
},
...
Is using cellRender (in cols definition (https://mui.com/x/react-data-grid/column-definition/#rendering-cells)) the only way to render my own green or red icons depending if value is true or false? Or is there a better way?

So far this seems the easiest way:
const columns: GridColumns = [
...
{
field: 'isPaid',
headerName: 'Is paid?',
type: 'boolean',
width: 140,
editable: true,
renderCell: (params) => {
return params.value ? (
<CheckIcon
style={{
color: theme.palette.success.light,
}}
/>
) : (
<CloseIcon
style={{
color: grey[500],
}}
/>
);
},
},
...

Related

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

i have a Data Grid table, there's a colomn that holds actions (edit and delete):
(Below 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 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.
How to properly render a button or icon inside Data Grid column?
I think you can try doing this. MUI exposes an actions column type that you can pass custom icons and implementations to. If you scroll down a bit on this link you can find a lot of column options.
Actions column
import { GridActionsCellItem, GridRowParams } from "#mui/x-data-grid-pro";
import EditIcon from "#mui/icons-material/Edit";
{
field: "actions",
type: "actions",
align: "left",
headerName: t("actions"),
getActions: (params: GridRowParams) => [
<GridActionsCellItem
key={0}
icon={<EditIcon titleAccess={t("edit")} color="primary" />}
label={t("edit")}
onClick={() => handleEditPressed(params)}
/>,
],
},
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.
},
},

Material-UI DataGrid - no checkbox onClick event?

I'm resurrecting a question I'd asked previously. I thought I'd come up with a good solution, but I'm wanting to find a more optimal solution. I want to enable the checkboxSelection prop so that each line has a checkbox, plus the Check All checkbox in the header, and on click of each of those I need to run an update function.
The issue I'm running in to however, is that there doesn't seem to be any sort of click handler for these checkboxes?
const columns: GridColumns = [
// {
// field: 'completed',
// headerName: '',
// editable: false,
// width: 45,
// sortable: false,
// hideSortIcons: true,
// headerClassName: 'checkbox-column',
// renderCell: (params: GridCellParams) => (
// <Checkbox
// checked={selectionModel.includes(params.id) || false}
// disableRipple
// disableFocusRipple
// onClick={() => handleToggleCompleted(params)}
// />
// ),
// },
{ field: 'title', headerName: 'Title', width: 280, editable: true },
{
field: 'quantity',
headerName: 'Quantity',
type: 'number',
editable: true,
width: 150,
},
{
field: 'delete',
headerName: '',
editable: false,
width: 45,
sortable: false,
headerClassName: 'delete-item-column',
hideSortIcons: true,
renderCell: (params: GridCellParams) => {
return (
<IconButton
className="delete-btn"
edge="end"
aria-label="comments"
disableRipple
disableFocusRipple
onClick={() => handleDelete(params)}>
<DeleteIcon className="delete" color="inherit" />
</IconButton>
);
},
},
];
<DataGrid
checkboxSelection
columnBuffer={0}
disableColumnMenu
disableColumnSelector
disableDensitySelector
disableSelectionOnClick
hideFooterPagination
hideFooter
rows={rows}
columns={columns}
onCellEditCommit={params => handleUpdate(params)}
/>
So if I had the checkboxSelection prop, how can I hook in to the onClick event for that specific checkbox?
Finally figured out a good solution!
I stumbled across the renderHeader option for defining columns, which allows me to define the onClick function.
const columns: GridColumns = [
{
field: 'completed',
editable: false,
width: 45,
sortable: false,
hideSortIcons: true,
headerClassName: 'checkbox-column',
renderCell: (params: GridCellParams) => (
<Checkbox
checked={selectionModel.includes(params.id) || false}
disableRipple
disableFocusRipple
onClick={() => handleToggleCompleted(params)}
/>
),
renderHeader: () => (
<Checkbox
checked={rows.every(r => r.completed) || false}
disableRipple
disableFocusRipple
onChange={e => handleToggleAllCompleted(e.target.checked)}
style={{ paddingLeft: '4px' }}
/>
),
},
{ field: 'title', headerName: 'Title', width: 425, editable: true },
{
field: 'delete',
headerName: '',
editable: false,
width: 45,
sortable: false,
headerClassName: 'delete-item-column',
hideSortIcons: true,
renderCell: (params: GridCellParams) => {
return (
<IconButton
className="delete-btn"
edge="end"
aria-label="comments"
disableRipple
disableFocusRipple
onClick={() => handleDelete(params)}>
<DeleteIcon className="delete" color="inherit" />
</IconButton>
);
},
},
];
<DataGrid
columnBuffer={0}
disableColumnMenu
disableColumnSelector
disableDensitySelector
disableSelectionOnClick
hideFooterPagination
hideFooter
rows={rows}
columns={columns}
onCellEditCommit={params => handleUpdate(params)}
/>

MUI Datagrid rendercell getValue return undefined

Since I pushed my code on production, I cant call anymore getValue inside renderCell
Environnement is the same as dev by the way
Here is the columns def:
const columns = [
{
field: 'edit',
headerName: 'Edit',
sortable: false,
width: 78,
renderCell: (params) => (
<div>
<EditProduct defaultCats={props.defaultCats} prodId={params.getValue('id')} productIdGL={params.getValue('productId')} />
</div>
),
align: "left",
},
{
field: 'active',
headerName: 'Off / On',
width: 104,
renderCell: (params) => (
<div><CustomSwitch
checked={Boolean(params.value)}
onChange={() => myswitch(params.getValue('id'), Boolean(params.value))}
name="switch-"
inputProps={{ 'aria-label': 'primary checkbox' }}
></CustomSwitch>
</div>
),
align: "left",
},
{ field: 'category_name', headerName: 'Catégorie', width: 120 },
{ field: 'item_name', headerName: 'Nom du produit', width: 220 },
{
field: 'price',
headerName: 'Prix de vente',
type: 'number',
width: 140,
},
{
field: 'profit',
headerName: 'Profit par vente',
type: 'number',
width: 160,
alt: 'Test'
},
{ field: 'type', headerName: 'Type', width: 90 },
{ field: 'id', headerName: '#', width: 80 },
];
Error:
Unhandled Runtime Error
TypeError: Cannot read property 'undefined' of undefined
Any help appreciate since this bug occur only on production
mui-core: 4.11.4
mui-datagrid: 4.0.0-alpha.26
params.getValue(params.id, 'id') || ''
Instead of
params.getValue('id')

Bind ag-grid with array

I have an array with values array=[3,4].I have to display the ag-grid values if it matches with array values.This is what i tried so far:
Attached is the plunkr :https://plnkr.co/edit/fKrvfzFYjdLbTLjFkqpY?p=preview
var array=[3,4];
var columnDefs = [
{headerName: "Jobs",field: "job", width: 90},
{headerName: "Location", field: "loc", width: 120 },
{headerName: "Value", field: "value", width: 120 }];
var rowData =[{job:'Developer',loc:'X',value:1},
{job: 'Manager',loc:'Y',value:2},
{job: 'Musician',loc:'Z',value:3},
{job: 'Manager',loc:'A',value:4},
{job: 'Tester',loc:'B',value:5},
{job: 'DBA',loc:'C',value:6}
];
var gridOptions = {
defaultColDef: {
sortable: true
},
columnDefs: columnDefs,
animateRows: true,
enableRangeSelection: true,
rowData: rowData,
checkbox : true
};
How to display the grid when value field value matches with array values.
Here is a plunkr with a working example - https://plnkr.co/edit/xdwI0Tql9I5n71D4QSDy?p=preview
Add a custom cellRenderer function like so in the column definition of values column
{
headerName: "Value",
field: "value",
width: 120,
cellRenderer: params => array.includes(params.value) ? params.value : ''
}

How to hide column in AG-Grid?

How to hide the column in AG-Grid and also it should not be displayed in Tool Panel...
var columnDefs = [{ headerName: "Stone_ID", field: "Stone_ID", width: 100, hide: "true" }]
You can set the column property of suppressToolPanel to true to achieve that.
var columnDefs = [
{
headerName: "Stone_ID",
field: "Stone_ID",
width: 100,
hide: true,
suppressToolPanel: true
}
]
If you are looking for dynamically show/hide columns follow below:
You can use either setColumnVisible or setColumnsVisible.
NOTE: those functions expect a colKey(s) which is related to the field you set in columnDefs.
columnDefs = [
{
headerName: "Name",
field: "name", // => that!
width: 150
},
{
headerName: "Last Name",
field: "last_name", // => that!
width: 150
},
// ...
];
When using setColumnVisible you can show/hide a single column
gridOptions.columnApi.setColumnVisible('name', false) //In that case we hide it
When using setColumnsVisible you can show/hide multiple columns
gridOptions.columnApi.setColumnsVisible(['name', 'last_name'], true) //In that case we show them
To do this programatically you can use:
Hide columns:
this.agGrid.columnApi.setColumnsVisible(["COL_ID_1", "COL_ID_2"], false);
Show columns:
this.agGrid.columnApi.setColumnsVisible(["COL_ID_1", "COL_ID_2"], true);
To do this for a whole column group you can use:
const group = this.columnApi.getColumnGroup("MY_GROUP");
group.children.forEach(child => this.columnApi.setColumnsVisible(child, false));
Posting late but It may helpful for others with some extra details:
If you want to hide your column on the grid you can use hide property to hide that column from the grid.
Only hide from grid colDef example:
colMainDef = [
{
headerName: 'Approved',
field: 'status',
hide: true
}]
But the same column will still be accessible on the side menu panel if you want to hide it from the side menu you can use one more property suppressColumnsToolPanel by making this true it will hide the column from the side menu.
Hide column from the grid as well as from side panel colDef example:
colMainDef = [
{
headerName: 'Approved',
field: 'status',
suppressColumnsToolPanel: true,
hide: true,
}]
Hope this will helps to hide/show columns as per your requirements.
var columnDefs = [{ headerName: "Stone_ID", field: "Stone_ID", width: 100, hide: true }]
{
...,
hide: true,
suppressColumnsToolPanel: true
}
In the package.json:
"dependencies": {
"#ag-grid-community/angular": "^24.1.0",
"#ag-grid-enterprise/all-modules": "^24.1.0",
...
}
hide: should get the value true, not the string "true" (like width: gets 100, not "100")
Just add "hide: true" in your column definition.
Ex:
var columnDefs = [{ headerName: "ABC", field: "XYZ", hide: true }]
hide column on load
{
headerName: 'ROE',
field: 'roe',
width: 100,
hide: true
},
based on selection you can show/hide it using
example
this.gridColumnApi.setColumnVisible('roe',true);
We can hide column dynamically in the following way using onColumnVisible listen event
const onColumnVisible = useCallback(params => {
if (params.source === 'toolPanelUi') {
const colId = params.column ? [ params.column.colId ] : params.columns.map(col => col.colId)
const value = columns.map(v => {
if (v.colId === colId.find(c => c === v.colId)) {
params.visible ? v.hide = false : v.hide = true
}
return v
})
if (value) {
setColumns(value)
}
}
}, [ gridParams, setColumns ])
<Grid onColumnVisible={onColumnVisible } />