Tree select example

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.

Complete React client module · MIT · Next.js and Vite

Interactive example

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>;
}