react-table keeps re-rendering unchanged cells - reactjs

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
}
]}
/>
);
}

Related

How can I remove column filters from a table in Antdesign on programmatical removal of columns?

In a ReactJS application (Typescript), using Antdesign 4.12.2, I am building a table that shows a list of record data over a number of columns. The columns shown can be modified by adding or removing them through a popover with a tree containing the various options.Columns may have associated filters.
It all works well, until you activate a filter and then remove the column. The column is then removed, but the filter is not deactivated, which means that the number of records shown does not go back to the number from before the filter was activated. When re-adding the column, the filter previously activated is still active.
How do I make sure that when a column is removed, any active filters are disabled?
Below is my code.
Note that as per this suggestion I've tried changing the filteredValue of a column to null, but does not appear to have any effect in the useEffect. Interestingly, using the 'clear' button, that I've added for debugging, does seem to work to a degree. It appears to remove all filters and shows all records after that. This only works when the column is visible, however. It does nothing after the column has been removed. Also, if you remove the column and re-add it after this, the filter will appear to work again. But if you re-added it after leaving the filters deselected, it will come back activated with the original filter selected. It's a hot mess!
Edit: I've updated the code below to also track and update filteredInfo, as per this article.
const isPresent = <T,>(t: T | undefined | null): t is T => t != null;
interface User {
username: string,
status: string
}
const ReportItemsTable: React.FC = () => {
const allColumnOptions = [
{
key: "username", title: "Username"
},
{
key: "status", title: "Status"
}
];
const items: User[] = [
{
status: "one",
username: "Piet"
},
{
status: "two",
username: "Saar"
},
{
status: "one",
username: "Jan"
},
{
status: "two",
username: "Klaas"
},
{
status: "one",
username: "Maartje"
},
{
status: "three",
username: "Sjeng"
},
{
status: "one",
username: "Elke"
},
{
status: "two",
username: "Twan"
},
{
status: "one",
username: "An"
},
{
status: "three",
username: "Nel"
},
];
const [filteredInfo, setFilteredInfo] = useState<Record<string, FilterValue | null>>({});
const possibleColumns: ColumnType<User>[] = [
{
title: "Username",
key: "username",
dataIndex: "username",
sorter: (a: User, b: User) => a.username.localeCompare(b.username),
render: (userName: string) => (<>{userName}</>)
},
{
title: "Status",
key: "status",
dataIndex: "status",
filteredValue: filteredInfo && filteredInfo["status"],
filters: [
{
text: "One",
value: "one"
},
{
text: "Two",
value: "two"
},
{
text: "Three",
value: "three"
},
],
onFilter: (value: ColumnFilterValue, user: User) => user.status === value,
sorter: (a: User, b: User) => a.status.localeCompare(b.status),
render: (status: string) => (<>{status}</>)
}
];
// Note that selectedColumns is controlled by checkedKeys. selectedColumns should not be modified directly.
const [checkedKeys, setCheckedKeys] = useState<Key[] | { checked: Key[]; halfChecked: Key[]; }>([]);
const [selectedColumns, setSelectedColumns] = useState<ColumnType<User>[]>(possibleColumns);
const getTreeData = (allOptions: DataNode[]): DataNode[] => {
return [{
key: "masterKey",
title: "(de)select all",
children: [...allOptions]
}];
};
// The useEffect below was originally only in charge of checking
// whether the checkedKeys had changed and accordingly adding or
// removing columns from the table. It was expanded to set the
// filteredValue to null if the column was unchecked.
useEffect(() => {
setFilteredInfo(filteredInfo => {
const newFilteredInfo = {...filteredInfo};
const visibleKeys = Array.isArray(checkedKeys) ? checkedKeys : checkedKeys.checked;
const invisibleKeys = possibleColumns.map(column => column.key).filter(isPresent).filter(columnKey => !visibleKeys.includes(columnKey));
invisibleKeys.forEach(key => delete newFilteredInfo[key]);
return newFilteredInfo;
});
if (Array.isArray(checkedKeys)) {
setSelectedColumns(possibleColumns
.map(column => {
if (!isPresent(column.key)) return column;
if (!checkedKeys.includes(column.key)) {
return {
...column,
filteredValue: null
}
}
return column;
})
.filter(column => checkedKeys
.map(checkedKey => checkedKey.toString())
.includes(column.key?.toString() ?? "")));
} else {
setSelectedColumns(possibleColumns
.map(column => {
if (!isPresent(column.key)) return column;
if (!checkedKeys.checked.includes(column.key)) {
return {
...column,
filteredValue: null
}
}
return column;
})
.filter(column => checkedKeys.checked
.map(checkedKey => checkedKey.toString())
.includes(column.key?.toString() ?? "")));
}
}, [checkedKeys]);
const filterTree =
<Tree
key={"columnfilter"}
checkable
defaultExpandedKeys={["masterKey"]}
checkedKeys={checkedKeys}
selectable={false}
onCheck={checkedKeys => {
setCheckedKeys(checkedKeys);
}}
treeData={getTreeData(allColumnOptions)}
/>
;
const columnFilterButton =
<Popover
placement="bottom"
title={"Select columns"}
content={filterTree}
trigger="click">
<Tooltip title={"Select columns"}>
<Button icon={<ViewWeekOutlinedIcon sx={{ fontSize: 17, marginTop: "2.5px" }}></ViewWeekOutlinedIcon>}>
</Button>
</Tooltip>
</Popover>
;
return (
<>
<Row style={{paddingTop: "10px", paddingBottom: "10px"}}>
<Col span={24} style={{ textAlign: "left" }}>
<Space>
<Button.Group>
{columnFilterButton}
</Button.Group>
</Space>
</Col>
</Row>
<Table
onChange={(pagination, filters) => setFilteredInfo(filters)}
columns={selectedColumns}
dataSource={items}
size="middle"
/>
<button onClick={() => {
setFilteredInfo({});
setSelectedColumns(selectedColumns.map(column => {
return {
...column,
filteredValue: null
};
}));
}
}>clear</button>
</>
);
};
export default ReportItemsTable;

Custom handler search filter table antd

I am using antd to create a table with filter feature,
but I got a problem, I want to custom filter search of antd to call api,
antd table
How can I do that with react and antd,
Here is my code
const columns: ColumnsType<Product> = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: (name, record) => (
<div className="flex items-center">
<Avatar src={record.avatar}>{name[0].toUpperCase()}</Avatar>
<span style={{ marginLeft: 10 }} className="whitespace-nowrap">
<a title="View & Edit" href={'/product/' + record.id}>
{name}
</a>
</span>
</div>
),
},
{
title: 'About',
dataIndex: 'about',
key: 'about',
render: (about: string) => <p className="text-ellipsis line-clamp-2">{about}</p>,
width: 400,
},
{
title: 'Categories',
dataIndex: 'categories',
key: 'categories',
filterSearch: true,
filters: categories!.map((category: Category) => ({ text: category.name, value: category.id })),
render: (categories: any) => {
console.log(categories);
return '-';
},
// width: 400,
},
{ title: 'Addresses', dataIndex: 'contract_addresses', key: 'address', render: addresses => addresses?.[0] },
];
To filter the table, I usually provide a function that filters the data before it is passed to the table (In my example the function getData. This function can also be used to adjust the filter accordingly. Here is an example, which also consists of a Search-Input to modify the search:
const CustomersTable = (props: any) => {
const [searchText, setSearchText] = useState<string | undefined>(undefined);
const [customers, setCustomers] = useState<ICustomer[]>([]);
const getData = (
sourceData: Array<ICustomer>,
searchText: string | undefined
) => {
if (!searchText) {
return sourceData;
}
return sourceData.filter((item) => {
const comparisonString = `${item.firstname.toLowerCase()}${item.familyname.toLowerCase()}`;
//here you can provide a more sophisticared search
return comparisonString.includes(searchText.toLowerCase());
});
};
const columns = [
{
title: "Vorname",
dataIndex: "firstname",
key: "firstname",
sorter: (a: ICustomer, b: ICustomer) => {
if (a.firstname.toLowerCase() > b.firstname.toLowerCase()) {
return -1;
} else if (a.firstname.toLowerCase() < b.firstname.toLowerCase()) {
return 1;
} else {
return 0;
}
},
},
{
title: "Nachname",
dataIndex: "familyname",
key: "familyname",
},
];
return (
<>
<Search
placeholder="Vorname, Nachname"
value={searchText}
onChange={(e) => {
setSearchText(e.target.value);
}}
/>
<Table
columns={columns}
dataSource={getData(customers, searchText)}
/>
</>
);
};

If Statement Inside Map

I currently have a DataGrid that is rendering data grabbed from my backend mongoDB. The data rendering is mapped to keys specified by the objects in the mongoDB document. In each document is a set of boolean values, and I am trying to check if any of those are true, if they are true it will render a Y in the repairsNeeded column for each row, if not, it will render an N. The main problem I am running into is where/how to check this. I have played with a few different ideas to no avail. Right now I have the repairsNeeded column for each row assigned to the document.isPowerCordDamaged (one of my booleans), which renders true or false depending on if its checked.
Code:
function Rounding() {
const [cartsRounded, setCartsRounded] = useState([]);
let navigate = useNavigate();
useEffect(() => {
userCartsRounded()
.then((response) => {
setCartsRounded(response.data);
})
.catch((err) => {
console.log(err);
});
}, []);
const columns = [
{
field: "serialNum",
headerName: "Cart Serial Number",
width: 250,
},
{
field: "pcNum",
headerName: "Workstation Number",
width: 250,
},
{
field: "dateLastRounded",
headerName: "Last Rounded On",
width: 250,
},
{
field: "repairsNeeded",
headerName: "Repairs?",
width: 100,
},
{
field: "quarter",
headerName: "Quarter",
width: 75,
},
];
const [sortModel, setSortModel] = React.useState([
{
field: "dateLastRounded",
sort: "desc",
},
]);
const rows = useMemo(
() =>
cartsRounded.map((row, index) => ({
...row,
id: index,
serialNum: row.cartSerialNumber,
pcNum: row.pcNumber,
dateLastRounded: moment(row.updatedAt).format("MM-D-YYYY"),
repairsNeeded: row.isPowerCordDamaged,
quarter: moment(row.updatedAt).format("Qo"),
})),
[cartsRounded]
);
return (
<div>
<IconButton
color="primary"
aria-label="new rounding"
component="span"
onClick={() => {
navigate("add_new_cart");
}}
>
<AddCircleOutline />
</IconButton>
<div style={{ height: 400, width: "100%" }}>
<DataGrid
component={Paper}
rows={rows}
columns={columns}
sortModel={sortModel}
pageSize={100}
rowsPerPageOptions={[100]}
/>
</div>
</div>
);
}
export default Rounding;
Document Example:
{
_id: new ObjectId("61b95e447aec51d938e856cc"),
cartSerialNumber: 'testytitit',
pcNumber: '14124f0sdf0sfs',
isPowerCordDamaged: false,
isFuseBlown: false,
isInverterBad: false,
isInterfaceDamaged: false,
isPhysicalDamage: false,
otherNotes: '',
roundedBy: '6186c13beb18d33d5088f7b2',
createdAt: 2021-12-15T03:17:24.495Z,
updatedAt: 2021-12-15T03:17:24.495Z,
__v: 0
}
I may not be understanding the question here. But I think what you are trying to do is have the repairsNeeded field have a Y or N rather than its boolean value.
Try this.
const rows = useMemo(
() =>
cartsRounded.map((row, index) => ({
...row,
id: index,
serialNum: row.cartSerialNumber,
pcNum: row.pcNumber,
dateLastRounded: moment(row.updatedAt).format("MM-D-YYYY"),
repairsNeeded: row.isPowerCordDamaged ? "Y" : "N" // short hand for if (row.isPowerCordDamaged === true) return "Y" else return "N",
quarter: moment(row.updatedAt).format("Qo"),
})),
[cartsRounded]
);
After looking it may be you want to return Y or N if any are true? In that case best pull it into a function.
const isRepairNeeded = (row) => {
if (row.isPowerCordDamaged) return "Y";
if (row.isFuseBlown) return "Y";
... rest of the ifs
return "N"; // N is only returned if none of the if statements === true;
}
const rows = useMemo(
() =>
cartsRounded.map((row, index) => ({
...row,
id: index,
serialNum: row.cartSerialNumber,
pcNum: row.pcNumber,
dateLastRounded: moment(row.updatedAt).format("MM-D-YYYY"),
repairsNeeded: isRepairNeeded(row) // call the function will return "Y" or "N",
quarter: moment(row.updatedAt).format("Qo"),
})),
[cartsRounded]
);

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);
}
}
},
};
}}
/>

Antd UI Table: Dynamically add/delete columns

Based on ANTD's Table example: https://ant.design/components/table/#components-table-demo-edit-cell, I would like to replicate this, with the addition of having the ability to add/delete new columns. The sample from the link above only illustrates how to add new rows.
Here's the code from the sample:
import { Table, Input, Button, Popconfirm, Form } from 'antd';
const FormItem = Form.Item;
const EditableContext = React.createContext();
const EditableRow = ({ form, index, ...props }) => (
<EditableContext.Provider value={form}>
<tr {...props} />
</EditableContext.Provider>
);
const EditableFormRow = Form.create()(EditableRow);
class EditableCell extends React.Component {
state = {
editing: false,
}
componentDidMount() {
if (this.props.editable) {
document.addEventListener('click', this.handleClickOutside, true);
}
}
componentWillUnmount() {
if (this.props.editable) {
document.removeEventListener('click', this.handleClickOutside, true);
}
}
toggleEdit = () => {
const editing = !this.state.editing;
this.setState({ editing }, () => {
if (editing) {
this.input.focus();
}
});
}
handleClickOutside = (e) => {
const { editing } = this.state;
if (editing && this.cell !== e.target && !this.cell.contains(e.target)) {
this.save();
}
}
save = () => {
const { record, handleSave } = this.props;
this.form.validateFields((error, values) => {
if (error) {
return;
}
this.toggleEdit();
handleSave({ ...record, ...values });
});
}
render() {
const { editing } = this.state;
const {
editable,
dataIndex,
title,
record,
index,
handleSave,
...restProps
} = this.props;
return (
<td ref={node => (this.cell = node)} {...restProps}>
{editable ? (
<EditableContext.Consumer>
{(form) => {
this.form = form;
return (
editing ? (
<FormItem style={{ margin: 0 }}>
{form.getFieldDecorator(dataIndex, {
rules: [{
required: true,
message: `${title} is required.`,
}],
initialValue: record[dataIndex],
})(
<Input
ref={node => (this.input = node)}
onPressEnter={this.save}
/>
)}
</FormItem>
) : (
<div
className="editable-cell-value-wrap"
style={{ paddingRight: 24 }}
onClick={this.toggleEdit}
>
{restProps.children}
</div>
)
);
}}
</EditableContext.Consumer>
) : restProps.children}
</td>
);
}
}
class EditableTable extends React.Component {
constructor(props) {
super(props);
this.columns = [{
title: 'name',
dataIndex: 'name',
width: '30%',
editable: true,
}, {
title: 'age',
dataIndex: 'age',
}, {
title: 'address',
dataIndex: 'address',
}, {
title: 'operation',
dataIndex: 'operation',
render: (text, record) => (
this.state.dataSource.length >= 1
? (
<Popconfirm title="Sure to delete?" onConfirm={() => this.handleDelete(record.key)}>
Delete
</Popconfirm>
) : null
),
}];
this.state = {
dataSource: [{
key: '0',
name: 'Edward King 0',
age: '32',
address: 'London, Park Lane no. 0',
}, {
key: '1',
name: 'Edward King 1',
age: '32',
address: 'London, Park Lane no. 1',
}],
count: 2,
};
}
handleDelete = (key) => {
const dataSource = [...this.state.dataSource];
this.setState({ dataSource: dataSource.filter(item => item.key !== key) });
}
handleAdd = () => {
const { count, dataSource } = this.state;
const newData = {
key: count,
name: `Edward King ${count}`,
age: 32,
address: `London, Park Lane no. ${count}`,
};
this.setState({
dataSource: [...dataSource, newData],
count: count + 1,
});
}
handleSave = (row) => {
const newData = [...this.state.dataSource];
const index = newData.findIndex(item => row.key === item.key);
const item = newData[index];
newData.splice(index, 1, {
...item,
...row,
});
this.setState({ dataSource: newData });
}
render() {
const { dataSource } = this.state;
const components = {
body: {
row: EditableFormRow,
cell: EditableCell,
},
};
const columns = this.columns.map((col) => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: record => ({
record,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave: this.handleSave,
}),
};
});
return (
<div>
<Button onClick={this.handleAdd} type="primary" style={{ marginBottom: 16 }}>
Add a row
</Button>
<Table
components={components}
rowClassName={() => 'editable-row'}
bordered
dataSource={dataSource}
columns={columns}
/>
</div>
);
}
}
ReactDOM.render(<EditableTable />, mountNode);
You can make your columns array a part of the state and update it through setState.
Here is a working codepen: https://codepen.io/gges5110/pen/GLPjYr?editors=0010
// State
this.state = {
dataSource: [{
key: '0',
name: 'Edward King 0',
age: '32',
address: 'London, Park Lane no. 0',
}, {
key: '1',
name: 'Edward King 1',
age: '32',
address: 'London, Park Lane no. 1',
}],
columns: [{
title: 'name',
dataIndex: 'name',
width: '30%',
editable: true,
}, {
title: 'age',
dataIndex: 'age',
}]
};
// Event to add new column
handleAddColumn = () => {
const { columns } = this.state;
const newColumn = {
title: 'age',
dataIndex: 'age',
};
this.setState({
columns: [...columns, newColumn]
});
}
// Render method
render() {
const { dataSource, columns } = this.state;
return (
<Table
dataSource={dataSource}
columns={columns}
/>
);
}

Resources