Skip to main content
09

File explorer

Mediumreactrecursiontreesa11y

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Build a file explorer that shows a nested folder structure, like the sidebar of a code editor. data.js holds the tree: a folder has a children array (which can be empty) and a file has none. Right now App.js lists only the top-level names.

Requirements

  • Render the whole tree, at any depth. Nested items are indented under their folder.
  • In every folder, folders come first, then files, and each group is sorted alphabetically. The data is deliberately not sorted.
  • Folders start collapsed. Clicking a folder expands it, and clicking again collapses it.
  • An expanded empty folder shows Empty folder.
  • Folders show 📁 when collapsed and 📂 when expanded. Files show 📄.
  • Don't mutate the data in data.js.

Accessibility

  • The tree is a <ul role="tree">. Each item is role="treeitem", and each folder's children are in a <ul role="group">.
  • Folders have aria-expanded, and the clickable part of a folder is a <button>.

Note

The preview updates as you type. There are no automated tests for this challenge yet: open every folder, including the empty one and the deepest one, then compare with the reference solution.

Follow-ups interviewers ask

  • Expand all and Collapse all buttons. Where does the expanded state need to live for that?
  • Full keyboard support from the WAI-ARIA tree pattern: arrows move between items, ArrowRight opens, ArrowLeft closes or goes to the parent.
  • Load a folder's children from an API the first time it opens.
  • Add, rename and delete files. How do you update a nested tree immutably?

The approach

A tree is a recursive structure, so the component is recursive too. Three small components call each other:

Loading diagram...

NodeList renders one level. For every folder it renders a Folder, which, when expanded, renders another NodeList for its children. The recursion stops at files and at collapsed folders. Depth is never tracked: indentation comes from the nested <ul>s and one CSS rule, .tree ul { padding-inline-start: 20px }.

Sorting without mutating

sortNodes copies the array ([...nodes]) before calling sort, which sorts in place. The comparator first puts folders before files, then compares names with localeCompare. Each level is sorted when it renders, so data.js is never touched.

Where the expanded state lives

Each Folder keeps its own expanded in useState. That is the simplest correct answer for this task, but it has a side effect worth knowing: collapsing a folder unmounts everything inside it, so the state of its subfolders is lost. Open src, then components, collapse src and open it again: components is closed.

If the interviewer wants nested folders to stay open, or asks for Expand all, lift the state up: keep a Set of expanded folder ids in FileExplorer and pass expanded and onToggle down. That is the usual follow-up.

Telling folders from files

isFolder checks Array.isArray(node.children), not node.children.length. An empty folder has children: [], which is still a folder, and checking length would turn it into a file.

Accessibility

role="tree", treeitem and group give screen readers the hierarchy, and aria-expanded on folder items says whether they're open. The folder name is a <button> so it can be focused and activated with the keyboard. The emoji icons are aria-hidden so they aren't read aloud.

What interviewers look for

  • A recursive component, and being comfortable explaining the recursion.
  • Sorting a copy, folders first.
  • Handling the empty-folder case.
  • A clear answer on local versus lifted expanded state, and the trade-off.

Reference solution

src/App.js

jsx
import { fileTree } from './data'
import FileExplorer from './FileExplorer'

export default function App() {
  return (
    <main className="app">
      <h1>Project files</h1>
      <FileExplorer data={fileTree} />
    </main>
  )
}

src/FileExplorer.js

jsx
import { useState } from 'react'

const isFolder = (node) => Array.isArray(node.children)

/** Folders first, then files, each group sorted by name. Returns a new array. */
function sortNodes(nodes) {
  return [...nodes].sort((a, b) => {
    if (isFolder(a) !== isFolder(b)) return isFolder(a) ? -1 : 1
    return a.name.localeCompare(b.name)
  })
}

export default function FileExplorer({ data }) {
  return (
    <ul className="tree" role="tree" aria-label="Project files">
      <NodeList nodes={data} />
    </ul>
  )
}

function NodeList({ nodes }) {
  return sortNodes(nodes).map((node) =>
    isFolder(node) ? <Folder key={node.id} node={node} /> : <File key={node.id} node={node} />,
  )
}

function Folder({ node }) {
  // Each folder remembers whether it is open. Collapsing a parent keeps its children's state.
  const [expanded, setExpanded] = useState(false)

  return (
    <li role="treeitem" aria-expanded={expanded} aria-selected={false}>
      <button type="button" className="node" onClick={() => setExpanded((value) => !value)}>
        <span aria-hidden="true">{expanded ? '📂' : '📁'}</span>
        {node.name}
      </button>
      {expanded && (
        <ul role="group">
          {node.children.length > 0 ? (
            <NodeList nodes={node.children} />
          ) : (
            <li className="empty" role="none">
              Empty folder
            </li>
          )}
        </ul>
      )}
    </li>
  )
}

function File({ node }) {
  return (
    <li role="treeitem" aria-selected={false}>
      <span className="node">
        <span aria-hidden="true">📄</span>
        {node.name}
      </span>
    </li>
  )
}