Cell validation for react data table - reactjs

I want to have the required field validation for a custom cell, i have in my data table. With the getprops i am able to style the cell but how can i display like a helper text or error for that cell? Is there any example?
Example:
const columns = [
{
Header: 'Things to Do',
accessor: 'item',
getProps: (rowInfo) => {
return {
style: {
backgroundColor: rowInfo && rowInfo.row.item === 'Do a thing' ? 'red' : null,
},
}
}
},
{
Header: '2020-04-01',
accessor: 'date.2020-04-01',
getProps: (rowInfo) => {
return {
style: {
backgroundColor: rowInfo && rowInfo.row['date.2020-04-01'] === 'Y' ? 'red' : null,
},
}
}
},

Related

Change text color based on classification - datatable Reactjs

I have created a data table using React Js. I have a column named Classification. I need to change the colors of a column text based on its classification. Means different colors for each classification.
For instance, Growth classification needs to be in green color, whereas Circular Classification needs to be in red.
const columns = [
{
name: i18n.t('Stock Symbol'),
selector: row => row.stockSymbol
},
{
name: i18n.t('Stock Name'),
selector: i18n.language == 'en' ? 'stockNameEn' :'stockNameAr'
},
{
name: i18n.t('Stock Classification'),
selector: i18n.language == 'en' ? 'stockClassification' :'stockClassificationAr',
className: 'red'
},
{
name: i18n.t('Sector') ,
selector: i18n.language == 'en' ? 'gicsSectorNameEn' :'gicsSectorNameAr'
},
{
name: i18n.t('Share Price') ,
selector: row => row.marketPrice,
style: row => row.marketPrice > 10 ? {color:'red'} : {color:'green'}
},
{
name: i18n.t('Market Cap') ,
selector: row => row.marketValueFormatted,
className: 'red'
}
]
<DataTable
noHeader
columns={columns}
data={getFilteredCompanyData}
highlightOnHover
className='react-dataTable'
pagination
paginationPerPage={10}
paginationRowsPerPageOptions={[5, 10, 15, 25, 50]}
paginationComponentOptions={{
rowsPerPageText: 'Records per page:',
rangeSeparatorText: 'out of',
conditionalRowStyles: { conditionalRowStyles }
}}
/>
I tried adding styles and classes into it but nothing worked.
Also tried conditionalRowStyles but didn't work
const conditionalRowStyles = [
{
when: row => row.marketPrice > 30,
style: { color: 'orange' },
},
{
when: row => row.stockClassification == "Growth",
style: { color: 'green' }
},
];
If you're using react-data-table-component npm-package you can check :
https://react-data-table-component.netlify.app/?path=/docs/api-custom-conditional-formatting--page

React material-ui datagrid editing Issue

I have created a Material UI DataGrid table and trying to make its fields editable. I am facing an issue while editing the fields using my custom logic. My custom editing logic works when I press enter however when I edit the value and then click outside of the column (somewhere else on the page) the internal value gets updated according to the logic however the displayed cell value doesn't match the updated value, it shows the user-edited value.
import React, { useEffect } from "react";
import { makeStyles, LinearProgress } from "#material-ui/core";
import {
DataGrid,
GridColDef,
GridOverlay,
GridCellEditCommitParams,
GridValueFormatterParams,
} from "#material-ui/data-grid";
const useStyles = makeStyles({
root: {
"& .super-app-theme--header": {
backgroundColor: "#f2f2f2",
},
},
muiGridRoot: {
maxHeight: "77px !important",
"& .MuiDataGrid-columnHeaderTitle": {
fontWeight: "600 !important" as any,
},
},
});
interface props {
coilId: string;
}
export default function TargetMechnicalPropsTable({
coilId,
}: props) {
const classes = useStyles();
const [rows, setRows] = React.useState<any>([
{
id: 1,
UpperLimitValue: 124.232,
lowerLimitValue: 24.232,
targetValue: 67.33,
element: "Yield Strength",
},
]);
const columns: GridColDef[] = [
{
field: "id",
hide: true,
headerClassName: "super-app-theme--header",
sortable: false,
flex: 1,
align: "center",
headerAlign: "center",
},
{
field: "element",
headerName: "Element",
headerClassName: "super-app-theme--header",
editable: false,
sortable: false,
flex: 1,
align: "center",
headerAlign: "center",
},
{
field: "targetValue",
headerName: "Target value",
headerClassName: "super-app-theme--header",
valueFormatter: (params: GridValueFormatterParams) => {
const valueFormatted = Number(params.value as number).toFixed(4);
return `${valueFormatted}`;
},
editable: true,
//type: "number",
sortable: false,
flex: 1,
align: "center",
headerAlign: "center",
},
{
field: "lowerLimitValue",
headerName: "Lower Limit",
headerClassName: "super-app-theme--header",
valueFormatter: (params: GridValueFormatterParams) => {
const valueFormatted = Number(params.value as number).toFixed(4);
return `${valueFormatted}`;
},
editable: true,
sortable: false,
flex: 1,
align: "center",
headerAlign: "center",
},
{
field: "UpperLimitValue",
headerName: "Upper Limit",
headerClassName: "super-app-theme--header",
sortable: false,
valueFormatter: (params: GridValueFormatterParams) => {
const valueFormatted = Number(params.value as number).toFixed(4);
return `${valueFormatted}`;
},
editable: true,
flex: 1,
align: "center",
headerAlign: "center",
},
];
const handleCellEditCommit = React.useCallback(
({ id, field, value }: GridCellEditCommitParams) => {
const updatedRows = rows.map((row: any) => {
if (row.id === id) {
switch (field) {
case "lowerLimitValue":
if (
Number(value) < Number(row.targetValue) &&
Number(value) < Number(row.UpperLimitValue)
) {
return { ...row, lowerLimitValue: Number(value) };
} else {
return {
...row,
lowerLimitValue: Number(row.lowerLimitValue),
};
}
case "UpperLimitValue":
if (
Number(value) > Number(row.targetValue) &&
Number(value) > Number(row.lowerLimitValue)
) {
return { ...row, UpperLimitValue: Number(value) };
} else {
return {
...row,
UpperLimitValue: Number(row.UpperLimitValue),
};
}
case "targetValue":
if (
Number(value) > Number(row.lowerLimitValue) &&
Number(value) < Number(row.UpperLimitValue)
) {
return { ...row, targetValue: Number(value) };
} else {
return {
...row,
targetValue: Number(row.targetValue),
};
}
}
}
return row;
});
setRows(updatedRows);
},
[rows]
);
return (
<div style={{ width: "100%" }} className={classes.root}>
<DataGrid
classes={{
root: classes.muiGridRoot,
}}
rows={rows}
columns={columns}
hideFooterPagination
hideFooter
disableColumnMenu
disableColumnFilter
disableColumnSelector
autoHeight
disableExtendRowFullWidth
density="compact"
onCellEditCommit={handleCellEditCommit}
/>
</div>
);
}
Please let me know what needs to be done for my custom logic to work when the user clicks outside of the column while editing it so that the user displayed value matches with the internal logic value.
Thank you!

How to use rowspan in react-table

Any idea how to use rowSpan in react table. for below example usernameFormatter there are multiple values.
Note: attach picture is copied but that's looks like what I wanted
const columns = [
{
accessor: "id",
show: false,
},
{
Header: "Username",
id: "username",
accessor: "username",
Cell: this.usernameFormatter,
enableRowSpan: true
}
]
<ReactTable
data={this.state.users}
filterable={true}
columns={columns}
defaultPageSize={18}
getTdProps={(state, rowInfo, column) => {
const index = rowInfo ? rowInfo.index : -1;
return {
onClick: (e, handleOriginal) => {
if (column.Header === undefined) {
handleOriginal();
} else {
if (rowInfo !== undefined) {
this.selectedRow = index;
this.onRowSelect(rowInfo.original.id);
}
}
},
};
}}
/>

how to Customer table antd formatNumber

https://ant.design/components/table/
I want to convert numbers to money using Table antd In line with this example I'm so confused, please help me, I hurry because I have to submit the last project before I graduate.
const timeConverter = rawDate => moment(rawDate).tz("Thai/Bangkok").format('L');
const { pagination } = this.props;
const columns = [
{
title: "ID",
dataIndex: "id",
align: "center",
width: "60px",
height: "30px",
},
{
title:"วันที่บันทึก",
dataIndex:"createdAt",
align:"center",
width:"200",
format:"0,0",
render: createdAt => timeConverter(createdAt)
},
{
title:"อ้างอิงใบเสร็จเลขที่ ",
dataIndex:"re_reference",
align:"center",
width:"200"
},
{
title:"ชื่อบริการ/สินค้า",
dataIndex:"re_pro_name",
align:"center",
width:"350",
},
{
title:"รายละเอียด",
dataIndex:"re_detail",
align:"center",
width:"100",
},
{
title:"รหัสสมาชิก (ถ้ามี)",
dataIndex:"re_cus_name",
align:"center",
width:"200",
},
{
title:"ประเภทรับ-จ่าย",
dataIndex:"re_type",
align:"center",
width:"350",
},
{
title:"ราคาต่อหน่วย",
dataIndex:"re_price",
align:"center",
width:"300",
// render: re_price => numeral('$0,0.00')(re_price)
render:(text, record) => (
<span> </span>
)
},
render: value => ${value}.00.replace(/\B(?=(\d{3})+(?!\d))/g, ',') //convert number monney

react-table keeps re-rendering unchanged cells

I am using react-table plugin, and my cells keep re-rendering while I am changing the applied searching filter even though their values aren't changed.
As seen in the video, name and debt TDs keep updating, even though their values are static.
https://i.imgur.com/2KkNs9f.mp4
I imagine, that may impact performance on larger tables.
Is there any fix? Or am I doing anything wrong?
Thanks.
Edit:
Code has been requested. Not much to show, basically everything done as in documentation.
Rendering part:
render(){
const columns = [
{
Header: "Name",
accessor: "name",
className: css.cell,
headerClassName: css.cell,
filterMethod: (filter, row) => {
return row[filter.id]
.toLowerCase()
.includes(filter.value.toLowerCase());
},
Cell: props => {
return <span>{props.value}</span>;
}
},
{
Header: "Tc",
accessor: d => {
const date = d.lastChange;
if (date.length) {
const s = date.split(" ");
const s2 = s[0].split("/");
const mdy = [s2[1], s2[0], s2[2]].join("/");
const his = s[1];
return Date.parse(mdy + " " + his);
}
return "";
},
id: "lastChange",
Cell: props => {
return <ArrowTime lastChange={props.value}></ArrowTime>;
},
headerClassName: css.cell,
className: css.cell
},
{
Header: "Debt",
accessor: d => Number(d.lastDebt),
id: "lastDebt",
headerClassName: css.cell,
className: css.cell,
Cell: props => {
return <span className="number">{props.value}</span>;
},
getProps: (state, rowInfo, column) => {
return {
style: {
background: rowInfo ? this.getColor(rowInfo.row.lastDebt) : null
}
};
}
}
];
return (
<ReactTable
data={this.props.table}
columns={columns}
minRows={0}
showPagination={false}
NoDataComponent={CustomNoDataComponent}
className={css.table}
resizable={false}
filtered={[{ id: "name", value: this.props.filter }]}
getTrProps={(state, rowInfo) => {
return {
className: rowInfo ? css.subRow : ""
};
}}
getTrGroupProps={(state, rowInfo) => {
return {
className: rowInfo ? css.row : ""
};
}}
getTbodyProps={props => {
return {
className: props ? css.tbody : ""
};
}}
getTheadProps={props => {
return {
className: props ? css.thead : ""
};
}}
defaultSorted={[
{
id: "lastDebt",
desc: true
}
]}
/>
);
}

Resources