Remove all selected tree items from multiselect tree #29823
-
Hi, I've created a multiselect tree and want to add a button that removes all checked items with one click. I saw an example in the docs where you can add and remove one item at a time, but that was for single-select and didn't seem applicable for my use-case. Is there a way to reset the checkedItems value on treeProps? Here's some code to clarify my question: https://codesandbox.io/s/competent-thompson-xnmzgf?file=/src/example.tsx |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Here's an updated version of your code: https://codesandbox.io/s/awesome-wescoff-rxxyhr?file=/src/example.tsx Also, here's a TS playground link just in case the codesandbox goes down: export const Selection = () => {
const [checkedItems, setCheckedItems] = React.useState(
() => new Map<TreeItemValue, TreeSelectionValue>([["1-2", true]])
);
const flatTree = useHeadlessFlatTree_unstable(items, {
defaultOpenItems: ["1", "2", "2-1", "2-2"],
checkedItems,
selectionMode: SELECTION_MODE,
onCheckedChange: (event, data) => setCheckedItems(data.checkedItems)
});
// Should clear the checked items array
const onClearAll = () => {
// Reset the checked items to be unchecked
setCheckedItems(new Map());
};
return (
<>
<Button onClick={onClearAll}>Clear all</Button>
<FlatTree {...flatTree.getTreeProps()} aria-label="Selection">
{Array.from(flatTree.items(), (flatTreeItem) => {
const { content, ...treeItemProps } = flatTreeItem.getTreeItemProps();
return (
<FlatTreeItem {...treeItemProps} key={flatTreeItem.value}>
<TreeItemLayout>{content}</TreeItemLayout>
</FlatTreeItem>
);
})}
</FlatTree>
</>
);
}; |
Beta Was this translation helpful? Give feedback.
useHeadlessFlatTree
allows you to pass a controlled value ofcheckedItems
and a callback to when you should update that state withonChekcedChange
, with that you can take control of the checked state. Once in control of the checked state, to reset it simply set the state to be an empty iterable (like a map, or an array for example).Here's an updated version of your code: https://codesandbox.io/s/awesome-wescoff-rxxyhr?file=/src/example.tsx
Also, here's a TS playground link just in case the codesandbox goes down: