I'm using antd
's table
component. I want to be able to filter the nodes down to any descendant.
I'm following the example of antd
's custom filter.
The example is not a tree structure, so here's a codesandbox with the right setup.
onFilter
seems to only loop over the root nodes. I don't know how to display Tesla > Model 3 it I type '3' in the search input. I know I have to return true
for Tesla, but I still don't understand how to then also return true
for Model 3
data
const data = [
{
key: "13",
name: "Tesla",
data: {
description: "Car manufacturer",
type: "Organization"
},
children: [
{
key: "4444",
name: "Model S",
data: {
description: "The fastest",
type: "Project"
}
},
{
key: "1444323",
name: "Model 3",
data: {
description: "The cheapest",
type: "Project"
}
}
]
},
{
key: "1",
name: "Microsoft",
data: {
description: "#1 software company",
type: "Organization"
}
}
];
App
class App extends React.Component {
state = {
searchText: '',
};
getColumnSearchProps = (dataIndex) => ({
filterDropdown: ({
setSelectedKeys, selectedKeys, confirm, clearFilters,
}) => (
<div style={{ padding: 8 }}>
<Input
placeholder={`Search ${dataIndex}`}
value={selectedKeys[0]}
onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
/>
<Button
type="primary"
onClick={() => this.handleSearch(selectedKeys, confirm)}
icon="search"
>
Search
</Button>
</div>
),
// onFilter seems to only loop over root nodes
onFilter: (value, record) => record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
render: (text) => (
<Highlighter
...
/>
),
})
render() {
const columns = [{
title: 'Name',
dataIndex: 'name',
key: 'name',
...this.getColumnSearchProps('name'),
}];
return <Table columns={columns} dataSource={data} />;
}
}
You can write a function to get a node's descendant values (based on dataIndex
) and filter for any of those having the search text too.
This would go inside of getColumnSearchProps before the return value:
const getDescendantValues = (record) => {
const values = [];
(function recurse(record) {
values.push(record[dataIndex].toString().toLowerCase());
record.children.forEach(recurse);
})(record);
return values;
}
...and this would be the updated onFilter:
onFilter: (value, record) => {
const recordName = record[dataIndex] || record.data[dataIndex];
const searchLower = value.toLowerCase();
return recordName
.toString()
.toLowerCase()
.includes(searchLower)
||
getDescendantValues(record).some(descValue => descValue.includes(searchLower));
}
I've forked your sandbox here: https://codesandbox.io/s/10jp9wql1j
...it includes all the root nodes with any descendant that satisfies your search condition. However it does not filter out the other descendant nodes that do not satisfy your search condition, unfortunately.