lara-light-indigo

TreeSelect

TreeSelect is a form component to choose from hierarchical data.

Single
Select Item
Multiple
Select Items
Checkbox
Select Items
Filter
Select Items
Initial Value
Select Item
Import via Module

import { TreeSelect } from 'primereact/treeselect';
 
Import via CDN

<script src="https://unpkg.com/primereact/core/core.min.js"></script>
<script src="https://unpkg.com/primereact/treeselect/treeselect.min.js"></script>
 
Getting Started

TreeSelect component requires an array of TreeNode objects as its options and keys of the nodes as its value.


<TreeSelect value={selectedNodeKey} options={nodes} onChange={(e) => setSelectedNodeKey(e.value)} placeholder="Select Item"></TreeSelect>
 

In example below, nodes are retrieved from a remote data source.


export const TreeSelectDemo = () => {
    const [nodes, setNodes] = useState(null);
    const [selectedNodeKey, setSelectedNodeKey] = useState(null);

    useEffect(() => {
        let nodeService = new NodeService();
        nodeService.getTreeNodes().then(data => setNodes(data));
    }, []);

    return (
        <TreeSelect value={selectedNodeKey} options={nodes} onChange={(e) => setSelectedNodeKey(e.value)} placeholder="Select Item"></TreeSelect>
    )
}
 

export class NodeService {

    getTreeNodes() {
        return fetch('data/treenodes.json').then(res => res.json()).then(d => d.root);
    }

}
 

The json response sample would be as following.


{
    "root": [
        {
            "key": "0",
            "label": "Documents",
            "data": "Documents Folder",
            "icon": "pi pi-fw pi-inbox",
            "children": [{
                "key": "0-0",
                "label": "Work",
                "data": "Work Folder",
                "icon": "pi pi-fw pi-cog",
                "children": [{ "key": "0-0-0", "label": "Expenses.doc", "icon": "pi pi-fw pi-file", "data": "Expenses Document" }, { "key": "0-0-1", "label": "Resume.doc", "icon": "pi pi-fw pi-file", "data": "Resume Document" }]
            },
            {
                "key": "0-1",
                "label": "Home",
                "data": "Home Folder",
                "icon": "pi pi-fw pi-home",
                "children": [{ "key": "0-1-0", "label": "Invoices.txt", "icon": "pi pi-fw pi-file", "data": "Invoices for this month" }]
            }]
        },
        {
            "key": "1",
            "label": "Events",
            "data": "Events Folder",
            "icon": "pi pi-fw pi-calendar",
            "children": [
                { "key": "1-0", "label": "Meeting", "icon": "pi pi-fw pi-calendar-plus", "data": "Meeting" },
                { "key": "1-1", "label": "Product Launch", "icon": "pi pi-fw pi-calendar-plus", "data": "Product Launch" },
                { "key": "1-2", "label": "Report Review", "icon": "pi pi-fw pi-calendar-plus", "data": "Report Review" }]
        },
        {
            "key": "2",
            "label": "Movies",
            "data": "Movies Folder",
            "icon": "pi pi-fw pi-star-fill",
            "children": [{
                "key": "2-0",
                "icon": "pi pi-fw pi-star-fill",
                "label": "Al Pacino",
                "data": "Pacino Movies",
                "children": [{ "key": "2-0-0", "label": "Scarface", "icon": "pi pi-fw pi-video", "data": "Scarface Movie" }, { "key": "2-0-1", "label": "Serpico", "icon": "pi pi-fw pi-video", "data": "Serpico Movie" }]
            },
            {
                "key": "2-1",
                "label": "Robert De Niro",
                "icon": "pi pi-fw pi-star-fill",
                "data": "De Niro Movies",
                "children": [{ "key": "2-1-0", "label": "Goodfellas", "icon": "pi pi-fw pi-video", "data": "Goodfellas Movie" }, { "key": "2-1-1", "label": "Untouchables", "icon": "pi pi-fw pi-video", "data": "Untouchables Movie" }]
            }]
        }
    ]
}
 
TreeNode API utilized by the TreeSelect
NameTypeDefaultDescription
keyanynullUnique key of the node.
labelstringnullLabel of the node.
dataanynullData represented by the node.
iconstringnullIcon of the node to display next to content.
childrenTreeNode[]nullAn array of treenodes as children.
stylestringnullInline style of the node.
classNamestringnullStyle class of the node.
selectablebooleannullWhether the node is selectable when selection mode is enabled.
leafbooleannullSpecifies if the node has children. Used in lazy loading.
Selection

TreeSelect supports "single", "multiple" and "checkbox" selection modes. Define selectionMode, value and onChange properties to control the selection. In single mode, selectionKeys should be a single value whereas in multiple or checkbox modes an object is required. By default in multiple selection mode, metaKey is necessary to add to existing selections however this can be configured with metaKeySelection property. Note that in touch enabled devices, Tree does not require metaKey.


import React, {Component} from 'react';
import {TreeSelect} from 'primereact/treeselect';
import {NodeService} from '../service/NodeService';

export const TreeSelectionDemo = () => {

    const [nodes, setNodes] = useState(null);
    const [selectedNodeKey1, setSelectedNodeKey1] = useState(null);
    const [selectedNodeKey2, setSelectedNodeKey2] = useState(null);
    const [selectedNodeKey3, setSelectedNodeKey3] = useState(null);

    useEffect(() => {
        let nodeService = new NodeService();
        nodeService.getTreeNodes().then(data => setNodes(data));
    }, [])

    return (
        <div>
            <h5>Single Selection</h5>
            <TreeSelect value={selectedNodeKey1} options={nodes} selectionMode="single" onChange={e => setSelectedNodeKey1(e.value)} />

            <h5>Multiple Selection</h5>
            <TreeSelect value={selectedNodeKey2} options={nodes} selectionMode="multiple" onChange={e => setSelectedNodeKey2(e.value)} />

            <h5>Checkbox Selection</h5>
            <TreeSelect value={selectedNodeKey3} options={nodes} selectionMode="checkbox" onChange={e => setSelectedNodeKey3(e.value)} />
        </div>
    )
}
 
Value Format

Value passed to and from the TreeSelect via the value property should be a an object with key-value pairs where key is the node key and value is a boolean to indicate selection. On the other hand in "checkbox" mode, instead of a boolean, value should be an object that has "checked" and "partialChecked" properties to represent the checked state of a node. Best way to clarify it is prepopulating a TreeSelect with an existing value.


data() {
    return {
        selectedNodeKey1: '2-1',
        selectedNodeKey2: {'1-1': true, '0-0-0': true},
        selectedNodeKey3: {'1': {checked: true, partialChecked: true}, '1-0': {checked: true}}
        nodes: null
    }
},
 
Chips Display

A comma separated list is used by default to display selected items whereas alternative chip mode is provided using the display property to visualize the items as tokens.


<TreeSelect value={selectedNodeKeys} display="chip" options={nodes} onChange={(e) => setSelectedNodeKeys(e.value)} selectionMode="multiple" placeholder="Select Items" />
 
Templating

Label of an option is used as the display text of an item by default, for custom content support define a valueTemplate that gets the selected nodes as a parameter. In addition header, footer and emptyMessage templates are provided for further customization.


<TreeSelect value={selectedNodeKeys} options={nodes} onChange={(e) => setSelectedNodeKeys(e.value)} valueTemplate={<span>Custom Content</span>} placeholder="Select Items" />
 
Filtering

Filtering is enabled by setting the filter property to true, by default label property of a node is used to compare against the value in the text field, in order to customize which field(s) should be used during search define filterBy property.

In addition filterMode specifies the filtering strategy. In lenient mode when the query matches a node, children of the node are not searched further as all descendants of the node are included. On the other hand, in strict mode when the query matches a node, filtering continues on all descendants.


<TreeSelect options={nodes} filter />

<TreeSelect options={nodes} filter filterBy="data.name,data.age" />

<TreeSelect options={nodes} filter filterMode="strict" />
 
Properties
NameTypeDefaultDescription
idstringnullUnique identifier of the element.
valueanynullA single or an object of keys to control the selection state.
namestringnullName of the input element.
styleobjectnullInline style of the component.
classNamestringnullStyle class of the component.
disabledbooleanfalseWhen present, it specifies that the component should be disabled.
optionsarraynullAn array of options to display.
scrollHeightstring400pxMaximum height of the options panel.
placeholderstringnullHint text for the input field.
tabIndexnumbernullIndex of the element in tabbing order.
inputIdstringnullIdentifier of the input element.
ariaLabelstringnullUsed to define a string that labels the component.
ariaLabelledBystringnullContains the element IDs of labels.
selectionModestringnullDefines the selection mode, valid values "single", "multiple", and "checkbox".
panelClassNamestringnullStyle class of the overlay panel element.
panelStylestringnullInline style of the overlay panel element.
appendToDOM element | stringdocument.bodyDOM element instance where the overlay panel should be mounted. Valid values are any DOM Element and 'self'. The self value is used to render a component where it is located.
emptyMessagestringnullText to display when there is no data.
displaystringcommaDefines how the selected items are displayed, valid values are "comma" and "chip".
metaKeySelectionbooleantrueDefines how multiple items can be selected, when true metaKey needs to be pressed to select or unselect an item and when set to false selection of each item can be toggled individually. On touch enabled devices, metaKeySelection is turned off automatically.
valueTemplateanynullThe template of selected values.
panelHeaderTemplateanynullThe template of header.
panelFooterTemplateanynullThe template of footer.
transitionOptionsobjectnullThe properties of CSSTransition can be customized, except for "nodeRef" and "in" properties.
dropdownIconstringpi pi-chevron-downIcon class of the dropdown icon.
filterbooleanfalseWhen specified, displays an input field to filter the items.
filterValuestringnullWhen filtering is enabled, the value of input field.
filterBystringlabelWhen filtering is enabled, filterBy decides which field or fields (comma separated) to search against.
filterModestringlenientMode for filtering valid values are "lenient" and "strict". Default is lenient.
filterPlaceholderstringnullPlaceholder text to show when filter input is empty.
filterLocalestringundefinedLocale to use in filtering. The default locale is the host environment's current locale.
filterInputAutoFocusbooleantrueWhen the panel is opened, it specifies that the filter input should focus automatically.
resetFilterOnHidebooleanfalseClears the filter value when hiding the dropdown.
Events
NameParametersDescription
onShow-Callback to invoke when the overlay is shown.
onHide-Callback to invoke when the overlay is hidden.
onChangeevent.originalEvent: browser event
event.value: Selected node key(s).
Callback to invoke when selection changes.
onNodeSelectevent.originalEvent: browser event
event.node: Selected node instance.
Callback to invoke when a node is selected.
onNodeUnselectevent.originalEvent: browser event
event.node: Unselected node instance.
Callback to invoke when a node is unselected.
onNodeExpandevent.originalEvent: browser event
event.node: Expanded node instance.
Callback to invoke when a node is expanded.
onNodeCollapseevent.originalEvent: browser event
event.node: Collapsed node instance.
Callback to invoke when a node is collapsed.
onFilterValueChangeevent.originalEvent: Browser event
event.value: the filtered value
Callback to invoke when filter value changes.
Methods
NameParametersDescription
filtervalue: the filter valueFilters the data.
Styling

Following is the list of structural style classes

NameElement
p-treeselectContainer element.
p-treeselect-label-containerContainer of the label to display selected items.
p-treeselect-labelLabel to display selected items.
p-treeselect-triggerDropdown button.
p-treeselect-panelOverlay panel for items.
p-treeselect-items-wrapperList container of items.
Dependencies

None.

Component Scale

Input Style

Ripple Effect

Free Themes

Built-in component themes created by the PrimeReact Theme Designer.

Bootstrap
Blue
Purple
Blue
Purple
Material Design
Indigo
Deep Purple
Indigo
Deep Purple
Material Design Compact
Indigo
Deep Purple
Indigo
Deep Purple
Tailwind
Tailwind Light
Fluent UI
Blue
PrimeOne Design - 2022 NEW
Lara Indigo
Lara Blue
Lara Purple
Lara Teal
Lara Indigo
Lara Blue
Lara Purple
Lara Teal
PrimeOne Design - 2021
Saga Blue
Saga Green
Saga Orange
Saga Purple
Vela Blue
Vela Green
Vela Orange
Vela Purple
Arya Blue
Arya Green
Arya Orange
Arya Purple
Premium Themes

Premium themes are only available exclusively for PrimeReact Theme Designer subscribers and therefore not included in PrimeReact core.

Soho Light
Soho Dark
Viva Light
Viva Dark
Mira
Nano

Legacy Free Themes

Nova
Nova Alt
Nova Accent
Luna Blue
Luna Green
Luna Amber
Luna Pink
Rhea

Premium Create-React-App Templates

Beautifully crafted premium create-react-app application templates by the PrimeTek design team.

Sakai
Atlantis
Freya
Ultima
Diamond
Sapphire
Serenity
Babylon
Avalon
Apollo
Roma