Forms

Tree select.

Choose related items in a hierarchy, with clear partial states and recoverable loading.

LIVE PREVIEWTry it. It works.

Install the source

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/tree-select.json

Registry setup · Examples · API and behavior · Open the playground

COMPLETE EXAMPLES

Use it in context.

Each example includes its imports, data and state. The preview runs that same source. Include the stylesheet once in your application.

Checked hierarchy with native form values

Select leaf IDs through a searchable tree. Parent states reflect loaded enabled children; native external forms retain values, controlled ownership and reset behaviour.

Keyboard

  • Arrow Down enters the tree from search. Arrow keys move, open and close branches.
  • Space selects loaded leaf choices; Enter opens a branch or toggles a leaf. Escape closes.
  • The application checks the required button field on submit and returns focus to it.

States covered

  • Mixed parent
  • Disabled ancestor and child
  • External native form
  • Uncontrolled reset
  • Controlled and read-only values
  • Unknown IDs retained
  • React prevented button reset

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-tree-select-native.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import {useId,useRef,useState} from 'react';
import {Button,TreeSelect,UIProvider,type TreeSelectNode} from '@bld8/ui';
const nodes:TreeSelectNode[]=[
  {id:'product',label:'Product',children:[
    {id:'interface',label:'Interface',description:'UI foundations and components.'},
    {id:'motion',label:'Motion',searchTerms:['animation','transitions']},
    {id:'legacy',label:'Archived patterns',disabled:true}]},
  {id:'research',label:'Research'},
  {id:'restricted',label:'Restricted',disabled:true,children:[{id:'private-notes',label:'Private notes'}]}
];
export default function TreeFormExample(){
  const formId=useId(),field=useRef<HTMLButtonElement>(null);
  const [owned,setOwned]=useState<string[]>(['research']),[status,setStatus]=useState(''),[error,setError]=useState(''),[changes,setChanges]=useState(0),[touched,setTouched]=useState(false),[preventReset,setPreventReset]=useState(false);
  return <UIProvider><div style={{display:'grid',gap:16}}>
    <label className="bui-choice"><input className="bui-checkbox" type="checkbox" checked={preventReset} onChange={event=>setPreventReset(event.target.checked)}/>Prevent tree reset</label>
    <form id={formId} aria-label="Tree selection form" onReset={event=>{if(preventReset)event.preventDefault();}} onSubmit={event=>{
      event.preventDefault();const data=new FormData(event.currentTarget),ids=data.getAll('access').map(String);
      if(!ids.length){setError('Choose at least one team area.');field.current?.focus();return;}
      setStatus(ids.join(',')+' | '+data.getAll('owned').join(',')+' | '+data.getAll('readonly').join(',')+' | '+data.getAll('disabled').length);
    }}><div className="actions"><Button type="submit">Read tree values</Button><Button type="reset" variant="secondary">Reset tree values</Button></div></form>
    <TreeSelect label="Team access" nodes={nodes} name="access" form={formId} defaultValue={['interface','unavailable-id']} defaultExpandedIds={['product','restricted']} required inputRef={field} error={error} hint="Parents select enabled leaf choices. Unavailable IDs are kept until you clear them." onBlur={()=>setTouched(true)} onValueChange={()=>{setError('');setChanges(count=>count+1);}}/>
    <TreeSelect label="Application access" nodes={nodes} name="owned" form={formId} value={owned} onValueChange={setOwned}/>
    <TreeSelect label="Read-only access" nodes={nodes} name="readonly" form={formId} defaultValue={['research']} readOnly/>
    <TreeSelect label="Disabled access" nodes={nodes} name="disabled" form={formId} defaultValue={['interface']} disabled/>
    <p role="status" aria-label="Tree form values">{status}</p>
    <p role="status" aria-label="Tree change count">{changes}</p>
    <p className="bui-hint">Tree field touched: {touched?'yes':'no'}</p>
  </div></UIProvider>;
}

Lazy choices with cancellation and recovery

A source change cancels pending requests. A retry keeps existing IDs, and selecting a partial parent never selects future children.

Keyboard

  • Space on an unloaded branch opens and loads it without selecting a branch ID.
  • Right Arrow expands or retries a branch. Space on a partial parent affects loaded enabled leaves only.
  • Search matches loaded labels, descriptions and aliases; it does not issue remote search.

States covered

  • Loading
  • Retry after failure
  • Incomplete parent
  • Empty branch
  • Invalid returned IDs
  • Source change and cancellation

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-tree-select-lazy.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import {useCallback,useRef,useState} from 'react';
import {Button,TreeSelect,UIProvider,type TreeSelectNode,type TreeSelectLoadRequest} from '@bld8/ui';
const roots:TreeSelectNode[]=[{id:'workspace',label:'Workspace',children:[
  {id:'guide',label:'Project guide'},
  {id:'design',label:'Design system',hasChildren:true},
  {id:'empty',label:'Empty collection',hasChildren:true},
  {id:'invalid',label:'Invalid example',hasChildren:true}
]}];
function pause(signal:AbortSignal){
  return new Promise<void>((resolve,reject)=>{
    if(signal.aborted){reject(new DOMException('Cancelled','AbortError'));return;}
    const abort=()=>{clearTimeout(timer);reject(new DOMException('Cancelled','AbortError'));};
    const timer=setTimeout(()=>{signal.removeEventListener('abort',abort);resolve();},350);
    signal.addEventListener('abort',abort,{once:true});
  });
}
export default function LazyTreeExample(){
  const attempts=useRef(0),hold=useRef(false),[source,setSource]=useState('studio'),[values,setValues]=useState<string[]>(['guide']),[changes,setChanges]=useState(0),[aborted,setAborted]=useState(0);
  const loadChildren=useCallback(async({id,signal}:TreeSelectLoadRequest)=>{
    try{if(hold.current){hold.current=false;await new Promise<void>((_resolve,reject)=>{if(signal.aborted)reject(new DOMException('Cancelled','AbortError'));else signal.addEventListener('abort',()=>reject(new DOMException('Cancelled','AbortError')),{once:true});});}else await pause(signal);}catch(error){if(signal.aborted)setAborted(count=>count+1);throw error;}
    if(id==='empty')return [];
    if(id==='invalid')return [{id:'guide',label:'Duplicate guide'}];
    if(id==='design'&&attempts.current++===0)throw new Error('Illustrative connection failure.');
    return [{id:source+'-colour',label:source==='studio'?'Colour system':'Colour archive',searchTerms:['palette']},{id:source+'-type',label:source==='studio'?'Type scale':'Type archive'}];
  },[source]);
  return <UIProvider><div style={{display:'grid',gap:16}}>
    <TreeSelect label="Project areas" nodes={roots} value={values} onValueChange={next=>{setValues(next);setChanges(count=>count+1);}} loadChildren={loadChildren} sourceKey={source} defaultExpandedIds={['workspace']} hint="The first Design system request fails. Retry keeps your selected guide."/>
    <div className="actions"><Button variant="secondary" onClick={()=>{hold.current=true;}}>Simulate slow tree request</Button><Button variant="secondary" onClick={()=>setSource(current=>current==='studio'?'archive':'studio')}>Switch tree source</Button><Button variant="ghost" onClick={()=>setValues(['guide'])}>Restore guide selection</Button></div>
    <p role="status" aria-label="Lazy tree values">{values.join(',')}</p>
    <p role="status" aria-label="Lazy tree changes">{changes}</p>
    <p role="status" aria-label="Lazy tree source">{source}</p>
    <p role="status" aria-label="Aborted tree requests">{aborted}</p>
    <p className="bui-hint">Illustrative local loader. Search covers loaded choices; the host owns its remote service.</p>
  </div></UIProvider>;
}

Quick reference

React / TypeScript
<TreeSelect label="Project areas" name="areas" nodes={nodes}
  value={areas} onValueChange={setAreas}
  loadChildren={loadChildren} />

In the workspace or ZIP starter, import components from @bld8/ui and include @bld8/ui/styles.css once. Registry installations use your local bld8/ source path. Wrap overlays in UIProvider.

API & behaviour

Canonical values are stable leaf IDs. Arrow keys navigate, Space changes checked state, and search retains matching hierarchy context. Parent actions affect only loaded enabled leaves; unknown lazy children are never silently selected. Incomplete ancestors cannot be fully checked. Lazy requests receive an AbortSignal and stale or invalid responses are rejected; retry preserves committed values. Controlled/default values, expansion, popup state, external form ownership, native reset, read-only/disabled states, hint/error and refs are explicit. Repeated hidden form values preserve selected IDs; required submission validation belongs to the host because the main entry is a button. The application owns hierarchy authorization and data persistence.

TreeSelect

TreeSelect public properties
PropTypeDefault
labelRequiredstring—
nodesRequiredreadonly TreeSelectNode[]—
classNamestring | undefined—
clearableboolean | undefinedtrue
defaultExpandedIdsreadonly string[] | undefined[]
defaultOpenboolean | undefinedfalse
defaultValuereadonly string[] | undefined[]
density"compact" | "comfortable" | undefined'comfortable'
disabledboolean | undefinedfalse
emptyMessagestring | undefined'No matching choices.'
errorstring | undefined—
expandedIdsreadonly string[] | undefined—
formstring | undefined—
formatValue((labels: readonly string[]) => string) | undefined

Formats the selected trigger text; full labels remain in its title.

—
hintstring | undefined—
inputRefRef<HTMLButtonElement> | undefined—
labelVisibility"hidden" | "visible" | undefined'visible'
loadChildrenTreeSelectChildrenLoader | undefined

Parent actions affect loaded enabled leaves only; future children are never auto-selected.

—
namestring | undefined—
onBlurFocusEventHandler<HTMLButtonElement> | undefined—
onExpandedChange((ids: string[]) => void) | undefined—
onOpenChange((open: boolean) => void) | undefined—
onOpenChangeComplete((open: boolean) => void) | undefined—
onValueChange((values: string[]) => void) | undefined—
openboolean | undefined—
placeholderstring | undefined'Choose items…'
popupDataAttributesRecord<`data-${string}`, string | number | boolean | undefined> | undefined

Non-reserved data-* metadata on the real popup, for composed editor ownership.

—
readOnlyboolean | undefinedfalse
requiredboolean | undefined

Announces required choice; the host validates this button field when submitting.

false
searchableboolean | undefinedtrue
sourceKeystring | undefined

Replace nodes, this key or the loader to invalidate requests and locally loaded children.

''
valuereadonly string[] | undefined

Canonical leaf IDs. Unknown IDs remain selected until the host or user removes them.

—

TreeSelectNode

TreeSelectNode public properties
PropTypeDefault
idRequiredstring

Stable and unique across the whole tree. Only leaf IDs are committed.

—
labelRequiredstring—
childrenreadonly TreeSelectNode[] | undefined

Undefined with hasChildren means this branch has not loaded yet.

—
descriptionstring | undefined—
disabledboolean | undefined—
hasChildrenboolean | undefined—
iconLucideIcon | undefined—
searchTermsreadonly string[] | undefined—

TreeSelectLoadRequest

TreeSelectLoadRequest public properties
PropTypeDefault
idRequiredstring—
nodeRequiredTreeSelectNode—
signalRequiredAbortSignal—

TreeSelectChildrenLoader

(request:TreeSelectLoadRequest)=>Promise<readonly TreeSelectNode[]>

Tables come from the public TypeScript declarations. Related types and function parameters are shown alongside their component. A dash means no default is declared at the public function boundary.

Related controls

Notes to self

Test this component with real content, keyboard input and both themes. The example is a starting point; labels, error handling and behaviour still need to fit the application.