React Ag-grid displaying - reactjs

When I add simple table on my page:
...
const [columnDefs] = useState([
{ headerName: "id", field: "id" },
{ headerName: "name", field: "name" },
{ headerName: "type", field: "type" },
]);
const defaultColDef = useMemo(() => {
return {
flex: 1,
minWidth: 140,
resizable: true,
};
}, []);
return (
<>
<div className="ag-theme-alpine" style={{ height: 400, width: 500 }}>
<AgGridReact
rowData={foundTemplates}
columnDefs={columnDefs}
getRowId={getRowId}
defaultColDef={defaultColDef}></AgGridReact>
pagination={false}
</div>
</>
);
foundTemplates has the following structure:
{ id: 1, name: "testName1", type: "TestRFQ", description: "description1", ownerCurrentUser: true, lastUsed: true },
{ id: 2, name: "testName2", type: "TestRFI", description: "description2", ownerCurrentUser: false, lastUsed: true },
{ id: 3, name: "testName3", type: "TestAuction", description: "description3", ownerCurrentUser: true, lastUsed: false },
{ id: 4, name: "testName4", type: "TestAuction", description: "description4", ownerCurrentUser: false, lastUsed: false },
I have a problem with displaying data in the right way:
all data is displaying in one column (despite I have some kind of column definitions with 3 fields at least). Also I've tried to remove a pagination block (pagination={false}), but it is still displaying.
How it looks now
In general I'm planning to use custom cell renderer for info displaying, but now I can't even display a simple data.

The root cause: I didn't import ag-grid css.

Related

How can I get the Material-UI DataGrid valueGetter to read data from a distinct object in an array?

I am developing a React Admin Page for Woocommerce. I want to retrieve the 'option' value from a specific object (product attribute with name = "Farbe") to display in a MUI DataGrid. I think that valueGetter would be the right approach, but can't get it to work.
Here's what I have:
The Woocommerce Product (row record):
{
"id": 232,
"date_created": "2022-08-14T08:02:18",
...
"attributes": [
{
"id": 0,
"name": "Farbe",
"option": "0045"
},
{
"id": 1,
"name": "Material",
"option": "Cotton"
},
...
],
...
}
The DataGrid column:
I am trying to select the object that has the value 'Farbe' on the key 'name' and access the value of the property 'option'
export const VariationColumns = [
{ field: 'id', headerName: 'Id', type: 'int', width: 100},
{ field: 'sku', headerName: 'SKU', type: 'string', width: 200},
{ field: 'name', headerName: 'Name', type: 'string', width: 500,
valueGetter: ( params ) => { return params.row.attributes[name =>'Farbe'].option }},
]
But it can't find the 'option' property:
"TypeError: Cannot read properties of undefined (reading 'option')"
Also tried:
valueGetter: ( params ) => { return params.row.attributes[name =>'Farbe'].option.value
valueGetter: ( params ) => { return params.row.attributes.name['Farbe'].option
valueGetter: ( params ) => { return params.row.attributes.name['Farbe'].option.value
Is there maybe a completely different approach needed to achieve this?
Any hint is greatly apreciated
Assuming that your rows prop looks like the record you provided above, you'd get it like so:
const rows = [
{
id: 232,
date_created: "2022-08-14T08:02:18",
attributes: [
{
id: 0,
name: "Farbe",
option: "0045",
},
{
id: 1,
name: "Material",
option: "Cotton",
},
],
},
];
const variationColumns = [
{ field: "id", headerName: "Id", type: "int", width: 100 },
{ field: "sku", headerName: "SKU", type: "string", width: 200 },
{
field: "attributes",
headerName: "Name",
type: "string",
width: 500,
valueGetter: (params) => {
return params.value.find((item) => item.name === "Farbe").option;
},
},
];
The key points are:
valueGetter params are cell params vs row params
The field property in the columns needs to match the field in your rows, so if you want to grab attributes you need to have field: "attributes" in your columns.
You can use params.value.find((item) => item.name === "Farbe").option) to return the object in the array that matches your desired search string, then access its option property.

MUI Datagrid, how to do conditional cellrender based on checkboxSelection

I am trying to make a conditional cellRender in a datagrid, if the row checkbox has been checked.
In my picture below, I want to remove the number counter component on that row when the checkbox is clicked.
Is there a way to do this with params? How else could I achieve this
const columns: GridColDef[] = [
{ field: 'id', headerName: 'LIO', flex: 1, minWidth: 80, maxWidth: 100 },
{ field: 'article', headerName: 'Artikel', flex: 1, minWidth: 100, maxWidth: 380 },
{ field: 'currentStock', headerName: 'Saldo', type: 'number', flex: 0.5, minWidth: 70 },
{
field: "inventedStock",
headerName: "Inventerat Antal",
flex: 0.5,
minWidth: 130,
type: 'number',
renderCell: params => {
if( params.row.checkboxSelection) {
return (
<ChooseNumber updateArticle={updateField} scannedArticle={{
article: {
compartments: undefined, units: [], price: 0, supplier: '', supplierArticleNr: '', name: '', alternativeNames: [], lioNr: '', alternativeProducts: [], Z41: false
},
unit: '', quantity: 2,
nr: 3,
}} ></ChooseNumber>
);
} else {
return(2);
}
}
},
I have tried to find a property in the datagrid params interface, but I can't figure it out. Any help much appreciated!
To my knowledge it is not possible to do it only using the params since they don't contain any information about the status of the checkbox.
However the selection of the DataGrid component can be controlled. This can help us track the checked ids which we can use to conditionally render our columns.
To track the checked rows we need to add an new state like so
const [selectedIds, setSelectedIds] = useState([]);
In the renderCell method we check if the id is in the selectedIds if so render the custom input, else render the other thing.
{
field: "inventedStock",
headerName: "Inventerat Antal",
flex: 0.5,
minWidth: 130,
type: "number",
renderCell: (params) => {
console.log(params);
if (selectedIds.includes(params.id) === false) {
return (
<ChooseNumber
updateArticle={updateField}
scannedArticle={{
article: {
compartments: undefined, units: [], price: 0, supplier: "", supplierArticleNr: "", name: "", alternativeNames: [], lioNr: "", alternativeProducts: [], Z41: false,
},
unit: "",
quantity: 2,
nr: 3,
}}
></ChooseNumber>
);
}
return "2";
},
}
The DataGrid component with your rows, columns and added selectionModel functionality
<DataGrid
rows={rows}
columns={columns}
...
selectionModel={selectedIds}
onSelectionModelChange={(newModel) => {
setSelectedIds(newModel);
}}
/>
I hope this helps with your project!

Material UI Datagrid not displaying Edit and Delete buttons in a row React js

I cannot be able to render the custom code for Edit and Delete in a row data.I am using MUI datatables passing columns and rows.But, for rows data is showing fine but for edit and delete [object object] is showing up instead of rendering the component.
Below is the code
In the map function I am adding the edit and delete code bu it is showing me like [object object] instead of the component. Here I am adding the edit and delete to display in the row with Icons.
import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, IconButton, Paper } from '#material-ui/core';
import React, { useState } from 'react';
import DeleteOutlineIcon from "#material-ui/icons/DeleteOutline";
import EditIcon from "#material-ui/icons/Edit";
import { DataGrid } from "#material-ui/data-grid";
export const DataTable = () => {
const columns = [
{ field: 'id', headerName: '# ID', width: 70, disableColumnMenu: true, disableColumnFilter: true, disableColumnSelector: true, sortable: false },
{ field: 'name', headerName: 'Name', width: 130, disableColumnMenu: true, disableColumnFilter: true, disableColumnSelector: true, sortable: false },
{ field: 'edit', headerName: ' ', width: 130 , disableColumnMenu: true, disableColumnFilter: true, disableColumnSelector: true, sortable: false },
{ field: 'delete', headerName: ' ', width: 130, disableColumnMenu: true, disableColumnFilter: true, disableColumnSelector: true, sortable: false }
];
const rows = [
{ id: 1, name: 'Snow', firstName: 'Jon', age: 35 },
{ id: 2, name: 'Lannister', firstName: 'Cersei', age: 42 },
{ id: 3, name: 'Lannister', firstName: 'Jaime', age: 45 },
{ id: 4, name: 'Stark', firstName: 'Arya', age: 16 },
{ id: 5, name: 'Targaryen', firstName: 'Daenerys', age: null },
{ id: 6, name: 'Melisandre', firstName: null, age: 150 },
{ id: 7, name: 'Clifford', firstName: 'Ferrara', age: 44 },
{ id: 8, name: 'Frances', firstName: 'Rossini', age: 36 },
{ id: 9, name: 'Roxie', firstName: 'Harvey', age: 65 },
];
const bodyData = rows.map( ( row, index ) => {
return {
...row,
"edit": (<IconButton
style={{ padding: "8px" }}
onClick={(e) => {
e.stopPropagation();
alert("test")
}}
id={`a_${row.id}`}
>
<EditIcon style={{ fontSize: "16px" }} />
</IconButton>),
"delete": (<IconButton
style={{ padding: "8px" }}
onClick={(e) => {
e.stopPropagation();
alert("test")
}}
id={`b_${row.id}`}
>
<DeleteOutlineIcon style={{ fontSize: "20px" }} />
</IconButton>)
}});
return (
<div style={{ height: 400, width: '100%' }}>
<DataGrid
rows={bodyData}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
/>
</div>
);
}
This is not the right way to do it, look at the documentation
It's the columns that must manage the UI and not the rows
const headers = columns.map( ( col ) => {
return {
field: col.field,
headerName: col.headerName,
width: col.width || "200",
renderCell: cellRenderer,
sortable: false,
};
});
const cellRenderer = (params) => {
return params.value;
};
Use renderCell and rendering the custom components

Ant table custom filter checkbox without dropdown

I am using ant table for my project where I want to filter records on click of checkbox inside my header row, when I click on check box all zero valued rows should be filtered and others should stay, is there any way I can do this?
Demo
You can achieve the desired feature by defining a custom columns title prop that renders a controlled Checkbox component in addition to the column's title string. When the Checkbox is true, you then filter out the table data based on your desired filter condition.
(As an aside, I did initially try to get the same functionality to work via the onFilter and filterIcon approach, but that approach proved unsuccessful.)
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { Table, Checkbox } from "antd";
import "./index.scss";
const DifferenceTable = (props) => {
const [isChecked, setIsChecked] = useState(false);
const data = [
{
date: "2020-06-17",
units: 2353.0,
amount: 8891206.27,
date: 2323,
units: 243234,
amount: 234234,
units_diff: 0,
amount_diff: 0
},
{
date: "2020-06-17",
units: 2353.0,
amount: 8891206.27,
date: 2323,
units: 243234,
amount: 234234,
units_diff: 1,
amount_diff: 1
}
];
const processedData = isChecked
? data.filter((datum) => datum.units_diff || datum.amount_diff)
: data;
const columns = [
{
title: "Bank",
children: [
{
title: "Trxn Date",
dataIndex: "date",
key: "date",
width: 100
},
{
title: "Sum Units",
dataIndex: "units",
key: "units",
width: 100
},
{
title: "Sum Amounts",
dataIndex: "amount",
key: "units",
width: 100
}
]
},
{
title: "CUSTOMER",
children: [
{
title: "Trxn Date",
dataIndex: "date",
key: "date",
width: 100
},
{
title: "Sum Units",
dataIndex: "units",
key: "units",
width: 100
},
{
title: "Sum Amounts",
dataIndex: "amount",
key: "amount",
width: 100
}
]
},
{
title: () => (
<div>
<span>Difference </span>
<Checkbox
checked={isChecked}
onChange={(e) => {
setIsChecked(e.target.checked);
}}
/>
</div>
),
dataIndex: "units_diff",
key: "units_diff",
children: [
{
title: "Units",
dataIndex: "units_diff",
key: "units_diff",
width: 100
},
{
title: "Amounts",
dataIndex: "amount_diff",
key: "amount_diff",
width: 100
}
],
align: "center"
}
];
return (
<Table
// rowKey="uid"
className="table diff_table"
columns={columns}
dataSource={processedData}
pagination={false}
scroll={{ y: 400, x: 0 }}
/>
);
};
ReactDOM.render(<DifferenceTable />, document.getElementById("container"));
A functional demo is available at the following CodeSandbox link

How to format a cell in react material-ui DataGrid

I have a react material-ui DataGrid.
One of the cells shows text data representing status, which I want to show in a graphical way - specifically bootstrap badge.
The DataGrid code is:
const ProcessesColumns: ColDef[] = [
{ field: 'id', headerName: 'ID' },
{ field: 'name', headerName: 'Name', width: 300 },
{ field: 'status', headerName: 'Status', width: 130 },
];
const processes = [
{
id: 1,
name: 'aaa',
status: 'Sucess',
},
{
id: 2,
name: 'bbb',
status: 'Fail',
},
{
id: 3,
name: 'ccc',
status: 'Sucess',
},
{
id: 4,
name: 'ddd',
status: 'Success',
},
{
id: 5,
name: 'eee',
status: 'Sucess',
},
{
id: 6,
name: 'fff',
status: 'Fail',
},
]
<DataGrid rows={processes} columns={ProcessesColumns} pageSize={10} />
I think you should check this
You can add a renderCell attribute on your status column definition
I think you can do it with renderCell. Here's an example of something similar, and I hope it helps.
I have a column which cells I want to format to have an icon and a value, and I created that in a format function:
const priorityFormater = (cell) => {
return (
<span>
<GrStatusGoodSmall className={taskPriorityColor(cell)} />
<span className="priority-span">{cell}</span>
</span>
);
};
Column definition:
{
field: "priority",
headerName: "Priority",
flex: 0,
minWidth: 140,
renderCell: (params) => {
return priorityFormater(params.value);
},
},
Result:

Resources