Reputation: 5363
I am trying to populate a Tree Select in ANT Design from API, the API Response type is so
projectData = ProjectData[];
export type ProjectData = {
key?: number;
projectId: number;
projectName: string;
description: string;
level: number;
parent: string;
parentId: number;
children: ProjectData[];
};
for TreeSelect I can't find an option to set title
to projectName
and value
to projectId
Tree select takes treeData
values in this format
const treeData = [
{
title: 'Node1',
value: '0-0',
children: [
{
title: 'Child Node1',
value: '0-0-1',
},
{
title: 'Child Node2',
value: '0-0-2',
},
],
},
{
title: 'Node2',
value: '0-1',
},
];
For example if I am using a a Cascader in ant design I can set the mapping with the fieldNames
prop like so
fieldNames={{ label: 'projectName', value: 'projectId', children: 'children' }}
is it possible at all to do something like this with TreeSelect?
I have a ProjectData[]
as mentioned above and I need to generate a tree select using that data. What is the best way?
Now If I use Cascader I can only select the Last(deepest) entry and not a node which is a parent. Thus I have to use Treeselect and Can't figure out how to map it properly.
------- Edit -----------
Added a sample of data with implementation of cascader and treeselect on codesandbox here
Upvotes: 1
Views: 5559
Reputation: 42228
Upon reading the docs, it seems like you can do this through the prop treeDataSimpleMode
. This would change the expected format of the treeData
from nested objects with children
to a flat array where each object has its own id
and a parent id pId
. It also appears that we can specify the property names for id
and pId
which is exactly what you want. We can change treeNodeLabelProp
from "label"
to "projectName"
and treeNodeFilterProp
from "value"
to "projectId"
.
So it seems like this might be all you need:
const MyTree = ({projectData}: {projectData: ProjectData[]}) => {
return (
<TreeSelect
treeData={projectData}
treeDataSimpleMode={{
id: 'projectId',
pId: 'parentId',
//rootPId can be set too
}}
treeNodeLabelProp="projectName"
treeNodeFilterProp="projectId"
/>
)
I can't really test this out without sample data so let me know if you get any errors.
Note that the typings in the antd package are not strict enough to detect changes in the formatting. The DataNode
interface makes all of the expected properties optional and has a string index signature to allow for any custom properties.
export interface DataNode {
value?: RawValueType;
title?: React.ReactNode;
label?: React.ReactNode;
key?: Key;
disabled?: boolean;
disableCheckbox?: boolean;
checkable?: boolean;
children?: DataNode[];
/** Customize data info */
[prop: string]: any;
}
Upvotes: 1