Checkboxes
API for multi-selecting items with checkboxes
Source | View Source |
Types | View Types |
Import | import { checkboxesFeature } from "@headless-tree/core |
Type Documentation | ConfigurationStateTree InstanceItem Instance |
The checkboxes feature allows users to multi-select items in a more permanent way than the normal selection feature, and visualize that state with checkboxes.
To use the feature, add the checkboxesFeature
to your feature array and render a checkbox component
in each of your tree item renderers with <input type="checkbox" {...item.getCheckboxProps()} />
.
As with other tree states, you can manage the checkbox state yourself with the config variable checkedItems
and the state change handler setCheckedItems
, or let Headless Tree manage this state for your.
propagateCheckedState
You can configure the behavior of clicking the checkbox on folders with the propagateCheckedState
option.
If enabled, toggling the checkbox state of a folder will toggle the state of all its leafs. The folder itself
will not be added to the checkedItems
state, but its checked state will be inferred from the state of
its leafs, being checked if all leafs are checked, and indeterminate if some leafs are checked
and some are not. You can also force folders to be independently checkable with canCheckFolders=true
,
though be aware that this will mean that folders will receive an explicit checked
state and will not
always be directly inferred from their leafs.
Trees with propagateCheckedState=true
is currently only supported for synchronous trees, not trees using the Async
Data Loader feature.
The default for propagateCheckedState
is true
for synchronous trees, and false
for asynchronous trees.
Below, you can experiment with the behavior for various combinations of propagateCheckedState
and canCheckFolders
:
Further customizing checkbox behavior
Similar to other Headless Tree features, you can customize feature behavior by overwriting any of the publicly exposed methods. Write a custom feature like so:
const checkboxOverride: FeatureImplementation<DemoItem> = {
itemInstance: {
toggleCheckedState: ({ item }) => {
// Custom logic to toggle the checked state of an item
},
getCheckedState: ({ tree, item }) => {
// Custom logic to determine the checked state of an item
return CheckedState.Indeterminate;
},
},
};
Then include it in your tree configuration:
const tree = createTree({
features: [...otherFeatures, checkboxesFeature, checkboxOverride],
// other tree config
});
You can find some samples below. In the select input below, you can choose between several samples.