React: how to get date from AG Grid row data - reactjs

Description: I'm trying to format the dateTime I get from an Activity data array. I'm certain the tabular data isn't empty or nullish since I've been using a different table library on which it displays.
Problem: The page displaying my activity list table crashes as it can not find a defined date in the data I've given it. This is likely due to me not guessing the data type of the valueGetter() when I define columns. The documentation and tutorial I've found were in javascript, so I couldn't get the answer from them.
Here's the ActivityModel interface:
export interface ActivityModel extends obj {
id: string
key: string
title: string
description: string
dateTime: Timestamp
duration: number
notes: string
type: string
activity: string
completed: boolean
material: string
size: string
assignedTo: string
value: string
unit: string
editable: boolean
}
And here's the Activities page:
const [columnDefs] = useState([
{ field: "title", headerName: "Title", filter: "agTextColumnFilter" },
{
field: "description",
headerName: "Description",
flex: 3,
filter: "agTextColumnFilter",
},
{
field: "startDate",
headerName: "Start Date",
flex: 2,
filter: "agDateColumnFilter",
valueGetter: (p: ActivityModel) => {
return formatDate(p.dateTime.toDate())
},
},
{
field: "completed",
headerName: "Completed",
filter: "agTextColumnFilter",
},
])
<div className="ag-theme-alpine" style={{ height: 400, width: 1200 }}>
<AgGridReact
defaultColDef={defaultColDef}
rowData={activities}
columnDefs={columnDefs}
onGridReady={pullActivities}
></AgGridReact>
</div>

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!

React Ag-grid displaying

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.

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

Is there a way to remove currency prefix from material-table react?

Is there any way to remove the currency prefix from react's material-table since I am using different currencies on the table, it becomes confusing to stick to just one prefix as I have a different column to display the type of currency
Any help would be appreciated, thanks
Here is a chunk of the source code for creating the table, I am getting the data from an API endpoint
<MaterialTable style={{marginLeft:'10px', marginRight:'10px'}}
title="INVOICES"
columns={[
{ title: 'Seller Name', field: 'seller' },
{ title: 'Buyer Name', field: 'buyer' },
{ title: 'Invoice No', field: 'invoice_number' },
{ title: 'Currency', field: 'currency' },
{ title: 'Amount', field: 'invoice_amount', type:'currency', currencySetting:{ currencyCode:'USD', minimumFractionDigits:0, maximumFractionDigits:2}},
{ title: 'Invoice Date', field: 'invoice_date' },
{ title: 'Eligible Date', field: 'date_eligible' },
{ title: 'Due Date', field: 'due_date' },
{ title: 'Status', field: 'status' },
]}
data={this.state.stats}
I'm not using material-table, but I played a little with it. This is the the source code of material-table where the error has created:
Intl.NumberFormat(currencySetting.locale !== undefined ? currencySetting.locale : 'en-US', {
style: 'currency',
currency: currencySetting.currencyCode !== undefined ? currencySetting.currencyCode : 'USD',
minimumFractionDigits: currencySetting.minimumFractionDigits !== undefined ? currencySetting.minimumFractionDigits : 2,
maximumFractionDigits: currencySetting.maximumFractionDigits !== undefined ? currencySetting.maximumFractionDigits : 2
}).format(value !== undefined ? value : 0);
It uses the Intl.NumberFormat standard Javascript function to format the currency. This function supports 47 country.
You can play with this function here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
For example for Hungary (my country) I can call it with:
new Intl.NumberFormat('hu', { style: 'currency', currency: 'huf' }).format(number);
So I should change the columnDefinition to:
{ title: 'Amount', field: 'invoice_amount', type:'currency', currencySetting:{ locale: 'hu',currencyCode:'huf', minimumFractionDigits:0, maximumFractionDigits:2}},
Please note, that I added a locale: 'hu' and I changed the currencyCode to 'huf'.
If your country is not in the supported countries. Try something else with similar formatting.

Resources