---
title: "File tree"
url: "https://sarthakmishra.com/riff-ui/components/file-tree"
description: "Composable, nestable file tree whose folders unfold and fold smoothly. Accessible React 19 source on UI SDK, installed with the shadcn CLI."
image: "https://sarthakmishra.com/og-images/riff-ui/file-tree.webp"
---

[View HTML](https://sarthakmishra.com/riff-ui/components/file-tree) · [Site index](https://sarthakmishra.com/llms.txt)

# File tree

Composable, nestable file tree whose folders unfold and fold smoothly.

## Installation

### CLI

```bash
pnpm dlx shadcn@latest add @riff/file-tree
```

### Manual

1. Copy the component

   Save this as `components/ui/file-tree.tsx`:

   ```tsx
   'use client';
   import {
     createContext,
     use,
     useId,
     useState,
     type MouseEvent,
     type ReactNode,
   } from 'react';
   import './file-tree.css';

   type TreeContext = {
     isOpen: (path: string) => boolean;
     toggle: (path: string) => void;
   };

   const Tree = createContext<TreeContext | null>(null);
   // The path of the folder a node sits in; the tree's root is ''.
   const Parent = createContext('');

   const NONE_OPEN: readonly string[] = [];

   const parentOf = (path: string) => path.slice(0, path.lastIndexOf('/'));

   function useTree() {
     const tree = use(Tree);
     if (!tree) throw new Error('Folder and File must be inside a FileTree');
     return tree;
   }

   /**
    * A tree of folders and files, nested as deep as you like. Folders unfold
    * and fold smoothly, and everything below moves with them. With
    * `singleOpen`, opening a folder closes its open siblings.
    *
    * Folder paths join names (or `value`s) with `/`, such as `src/components`;
    * `defaultOpen` takes these paths.
    */
   export function FileTree({
     label,
     singleOpen = false,
     defaultOpen = NONE_OPEN,
     children,
   }: {
     /** Names the tree's navigation for screen readers. */
     label: string;
     /** Keep at most one folder open within each folder. */
     singleOpen?: boolean;
     /** Folder paths open at first. */
     defaultOpen?: readonly string[];
     children: ReactNode;
   }) {
     const [open, setOpen] = useState<ReadonlySet<string>>(
       () => new Set(defaultOpen.map((path) => `/${path}`)),
     );
     const toggle = (path: string) =>
       setOpen((current) => {
         const next = new Set(current);
         if (next.has(path)) {
           next.delete(path);
           return next;
         }
         if (singleOpen) {
           // Open siblings close, with everything inside them; the folder's own
           // open descendants stay open for when it is shown again.
           const siblings = `${parentOf(path)}/`;
           for (const other of current)
             if (
               other.startsWith(siblings) &&
               other !== path &&
               !other.startsWith(`${path}/`)
             )
               next.delete(other);
         }
         next.add(path);
         return next;
       });
     return (
       <Tree value={{ isOpen: (path) => open.has(path), toggle }}>
         <nav className="riff-tree" aria-label={label}>
           <ul className="riff-tree-list">{children}</ul>
         </nav>
       </Tree>
     );
   }

   function Chevron() {
     return (
       <svg
         aria-hidden="true"
         className="riff-tree-chevron"
         viewBox="0 0 24 24"
         fill="none"
         stroke="currentColor"
         strokeWidth="2"
         strokeLinecap="round"
         strokeLinejoin="round"
       >
         <path d="m9 6 6 6-6 6" />
       </svg>
     );
   }

   function FolderIcon({ open }: { open: boolean }) {
     return (
       <svg
         aria-hidden="true"
         className="riff-tree-glyph"
         viewBox="0 0 24 24"
         fill="none"
         stroke="currentColor"
         strokeWidth="1.75"
         strokeLinecap="round"
         strokeLinejoin="round"
       >
         {open ? (
           <path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2" />
         ) : (
           <path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z" />
         )}
       </svg>
     );
   }

   function FileIcon() {
     return (
       <svg
         aria-hidden="true"
         className="riff-tree-glyph"
         viewBox="0 0 24 24"
         fill="none"
         stroke="currentColor"
         strokeWidth="1.75"
         strokeLinecap="round"
         strokeLinejoin="round"
       >
         <path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" />
         <path d="M14 2v4a2 2 0 0 0 2 2h4" />
       </svg>
     );
   }

   /**
    * A folder: a row that opens and closes its contents. Its icon turns into
    * the disclosure chevron on hover and focus.
    */
   export function Folder({
     name,
     value,
     icon,
     meta,
     children,
   }: {
     name: ReactNode;
     /** Its segment of the folder path; defaults to `name` when it is text. */
     value?: string;
     /** Replaces the folder glyph. */
     icon?: ReactNode;
     /** Text at the row's end, such as a count. */
     meta?: ReactNode;
     children?: ReactNode;
   }) {
     const tree = useTree();
     const parent = use(Parent);
     const panel = useId();
     const segment = value ?? (typeof name === 'string' ? name : panel);
     const path = `${parent}/${segment}`;
     const open = tree.isOpen(path);
     return (
       <li className="riff-tree-item">
         <button
           type="button"
           className="riff-tree-row riff-tree-folder"
           aria-expanded={open}
           aria-controls={panel}
           onClick={() => tree.toggle(path)}
         >
           <span className="riff-tree-icon">
             <span className="riff-tree-folder-glyph">
               {icon ?? <FolderIcon open={open} />}
             </span>
             <Chevron />
           </span>
           <span className="riff-tree-label">{name}</span>
           {meta !== undefined && <span className="riff-tree-meta">{meta}</span>}
         </button>
         <div
           id={panel}
           className="riff-tree-panel"
           data-open={open ? '' : undefined}
         >
           <div className="riff-tree-panel-body">
             <ul className="riff-tree-list riff-tree-nested">
               <Parent value={path}>{children}</Parent>
             </ul>
           </div>
         </div>
       </li>
     );
   }

   /** A file: a link when it has `href`, otherwise a button or plain row. */
   export function File({
     name,
     icon,
     meta,
     href,
     current = false,
     onClick,
   }: {
     name: ReactNode;
     /** Replaces the file glyph. */
     icon?: ReactNode;
     meta?: ReactNode;
     href?: string;
     /** The open file; it is highlighted and gets `aria-current`. */
     current?: boolean;
     onClick?: (event: MouseEvent<HTMLElement>) => void;
   }) {
     useTree();
     const content = (
       <>
         <span className="riff-tree-icon">{icon ?? <FileIcon />}</span>
         <span className="riff-tree-label">{name}</span>
         {meta !== undefined && <span className="riff-tree-meta">{meta}</span>}
       </>
     );
     let row = <span className="riff-tree-row">{content}</span>;
     if (href)
       row = (
         <a
           href={href}
           className="riff-tree-row"
           aria-current={current ? 'page' : undefined}
           onClick={onClick}
         >
           {content}
         </a>
       );
     else if (onClick)
       row = (
         <button
           type="button"
           className="riff-tree-row"
           aria-current={current ? 'true' : undefined}
           onClick={onClick}
         >
           {content}
         </button>
       );
     return (
       <li className="riff-tree-item" data-current={current ? '' : undefined}>
         {row}
       </li>
     );
   }
   ```

2. Copy its styles

   Save this beside it as `file-tree.css`:

   ```css
   /* Host roles first, system colours after: the component reads your theme
      when it has these properties and stays legible when it does not. */
   @layer components {
     .riff-tree {
       --riff-tree-indent: 0.75rem;
       --riff-tree-ease: cubic-bezier(0.23, 1, 0.32, 1);
       --riff-tree-icon-color: color-mix(
         in oklab,
         var(--color-muted-foreground, GrayText) 80%,
         transparent
       );
       color: var(--color-muted-foreground, GrayText);
       font-size: 0.875rem;
       line-height: 1.5;
     }
     .riff-tree-list {
       display: flex;
       flex-direction: column;
       gap: 1px;
       margin: 0;
       padding: 0;
       list-style: none;
     }
     /* Nested levels indent 12px, with a faint guide under the parent's icon
        that rows' hover fills cover. */
     .riff-tree-nested {
       position: relative;
       isolation: isolate;
       padding-block-start: 1px;
       padding-inline-start: var(--riff-tree-indent);
       &::before {
         content: '';
         position: absolute;
         top: 0.125rem;
         bottom: 0.125rem;
         z-index: -1;
         left: calc(0.5rem + 0.75rem - 0.5px);
         width: 1px;
         background-color: var(--color-border, GrayText);
       }
     }
     .riff-tree-row {
       display: flex;
       width: 100%;
       min-height: 1.875rem;
       align-items: center;
       gap: 0.5rem;
       border: 0;
       border-radius: 0.375rem;
       padding: 0.25rem 0.5rem;
       background: none;
       color: inherit;
       font: inherit;
       text-align: start;
       text-decoration: none;
       transition: background-color 150ms cubic-bezier(0, 0, 0.2, 1);
       &:is(a, button) {
         cursor: pointer;
       }
       &:focus-visible {
         outline: 2px solid var(--color-ring, Highlight);
         outline-offset: -2px;
       }
       &[aria-current] {
         background-color: var(--color-muted, Highlight);
         color: var(--color-foreground, CanvasText);
         font-weight: 500;
       }
     }
     .riff-tree-icon {
       display: inline-grid;
       width: 1.5rem;
       height: 1rem;
       flex-shrink: 0;
       place-items: center;
       color: var(--riff-tree-icon-color);
       & > *,
       & > * > svg {
         grid-area: 1 / 1;
       }
       & svg {
         width: 1rem;
         height: 1rem;
       }
     }
     .riff-tree-label {
       min-width: 0;
       flex: 1;
       overflow: hidden;
       text-overflow: ellipsis;
       white-space: nowrap;
     }
     .riff-tree-meta {
       flex: none;
       font-size: 0.75rem;
       font-variant-numeric: tabular-nums;
     }
     /* A folder's glyph swaps for the chevron on hover or keyboard focus; the
        chevron turns to point down while the folder is open. */
     .riff-tree-folder-glyph,
     .riff-tree-chevron {
       display: grid;
       transition:
         opacity 150ms cubic-bezier(0, 0, 0.2, 1),
         rotate 200ms cubic-bezier(0, 0, 0.2, 1);
     }
     .riff-tree-chevron {
       opacity: 0;
     }
     .riff-tree-folder[aria-expanded='true'] .riff-tree-chevron {
       rotate: 90deg;
     }
     .riff-tree-folder:focus-visible {
       .riff-tree-chevron {
         opacity: 1;
       }
       .riff-tree-folder-glyph {
         opacity: 0;
       }
     }
     /* The panel's one grid row eases between 0fr and its content's height,
        so rows below glide with it; the contents fade in a step behind.
        Opening runs a little longer than closing, so a closing folder gets out
        of the way. Visibility flips once the fold ends, keeping closed rows
        out of the tab order. */
     .riff-tree-panel {
       display: grid;
       grid-template-rows: 0fr;
       visibility: hidden;
       transition:
         grid-template-rows 200ms var(--riff-tree-ease),
         visibility 0s linear 200ms;
       &[data-open] {
         grid-template-rows: 1fr;
         visibility: visible;
         transition:
           grid-template-rows 300ms var(--riff-tree-ease),
           visibility 0s;
       }
     }
     .riff-tree-panel-body {
       min-height: 0;
       overflow: hidden;
       opacity: 0;
       translate: 0 -0.25rem;
       transition:
         opacity 150ms cubic-bezier(0, 0, 0.2, 1),
         translate 200ms var(--riff-tree-ease);
       .riff-tree-panel[data-open] > & {
         opacity: 1;
         translate: 0;
         transition:
           opacity 150ms cubic-bezier(0, 0, 0.2, 1) 35ms,
           translate 300ms var(--riff-tree-ease);
       }
     }
     @media (hover: hover) {
       .riff-tree-row:is(a, button):not([aria-current]):hover {
         background-color: var(--color-muted, ButtonFace);
         color: var(--color-foreground, CanvasText);
       }
       .riff-tree-folder:hover {
         .riff-tree-chevron {
           opacity: 1;
         }
         .riff-tree-folder-glyph {
           opacity: 0;
         }
       }
     }
     /* Reduced motion keeps the fade on open and drops all travel. */
     @media (prefers-reduced-motion: reduce) {
       .riff-tree-row,
       .riff-tree-folder-glyph,
       .riff-tree-chevron,
       .riff-tree-panel,
       .riff-tree-panel[data-open],
       .riff-tree-panel-body {
         transition: none;
       }
       .riff-tree-panel-body {
         translate: 0;
       }
       .riff-tree-panel[data-open] > .riff-tree-panel-body {
         transition: opacity 150ms cubic-bezier(0, 0, 0.2, 1);
       }
     }
   }
   ```

## Usage

```tsx
import { File, FileTree, Folder } from '@/components/ui/file-tree';

<FileTree label="Docs" singleOpen>
  <Folder name="Guides">
    <File name="Install" href="/docs/install" />
  </Folder>
  <Folder name="API">
    <File name="Client" href="/docs/client" />
  </Folder>
</FileTree>;
```

Nest `Folder`s as deep as you need. Opening or closing one eases its height, so everything below glides with it. Turn on `singleOpen` to keep one folder open per level; tick the box in the demo to try it. A folder’s path is its parents’ names joined by `/`, which is what `defaultOpen` takes.

## Props

| Prop                   | Type        | Default | Description                                      |
| ---------------------- | ----------- | ------- | ------------------------------------------------ |
| `FileTree.label`       | `string`    |         | Names the tree.                                  |
| `FileTree.singleOpen`  | `boolean`   | `false` | Opening a folder closes its siblings.            |
| `FileTree.defaultOpen` | `string[]`  | `[]`    | Folder paths open at first.                      |
| `Folder.name`          | `ReactNode` |         | The row’s text.                                  |
| `Folder.value`         | `string`    | `name`  | Its segment of the path.                         |
| `File.href`            | `string`    |         | Makes the row a link.                            |
| `File.current`         | `boolean`   | `false` | Highlights the row.                              |
| `icon, meta`           | `ReactNode` |         | Replace the glyph, or add text at the row’s end. |

## Structured data

```json
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "WebSite",
      "@id": "https://sarthakmishra.com/#website",
      "url": "https://sarthakmishra.com/",
      "name": "Sarthak Mishra",
      "publisher": {
        "@id": "https://sarthakmishra.com/#person"
      },
      "inLanguage": "en"
    },
    {
      "@type": "Person",
      "@id": "https://sarthakmishra.com/#person",
      "name": "Sarthak Mishra",
      "url": "https://sarthakmishra.com/about",
      "jobTitle": "Design Engineer",
      "image": "https://sarthakmishra.com/og-images/sarthak-mishra.webp",
      "sameAs": [
        "https://github.com/SarthakMishra",
        "https://www.linkedin.com/in/itssarthakmishra/",
        "https://x.com/MishraMishry"
      ]
    },
    {
      "@type": "WebPage",
      "@id": "https://sarthakmishra.com/riff-ui/components/file-tree#webpage",
      "url": "https://sarthakmishra.com/riff-ui/components/file-tree",
      "name": "File tree React Component - Riff UI",
      "description": "Composable, nestable file tree whose folders unfold and fold smoothly. Accessible React 19 source on UI SDK, installed with the shadcn CLI.",
      "inLanguage": "en",
      "isPartOf": {
        "@id": "https://sarthakmishra.com/#website"
      },
      "about": {
        "@id": "https://sarthakmishra.com/#person"
      }
    }
  ]
}
```
