June 28, 2026 at 07:53 PM EST
Playing with folders and subfolders in React with recursion
June 28, 2026 at 07:53 PM EST
Playing with folders and subfolders in React with recursion
My goal in this post is to outline and implement the logic of building an interactive directory tree in React with Python. I find this useful to learn if your app deals with data organization of photos, drawings, words, etc. It also serves as a great exercise hence why I wanted to take my time to explore the concepts in depth.
For this demonstration, I’ll build the category tree below with its associated initial data input: a flat array containing a list of categories. Each category may have a parent_id. The top level categories, nature and shapes, currently do not have parent_ids.
Category Tree

Initial Category Data
const categories = [
{ id: 1, name: "nature", parent_id: null },
{ id: 6, name: "shapes", parent_id: null },
{ id: 2, name: "flowers", parent_id: 1 },
{ id: 3, name: "trees", parent_id: 1 },
{ id: 4, name: "plants", parent_id: 1 },
{ id: 5, name: "poison-ivy", parent_id: 4 },
{ id: 7, name: "3D", parent_id: 6 },
{ id: 8, name: "2D", parent_id: 6 },
{ id: 9, name: "cylinders", parent_id: 7 },
{ id: 10, name: "squares", parent_id: 8 },
{ id: 11, name: "triangles", parent_id: 8 },
]
The first step is transforming our initial flat array into a structure we can easily perform lookups in. We could simply choose to work with what we have, the 1D array, but any search of a specific category would require a scan of the whole array. We can optimize the search by recursively bundling up the categories into parent-children entries.
def _build_category_tree(categories):
children_map = defaultdict(list)
# SETUP
for cat in categories:
children_map[cat.parent_id].append(cat)
def dfs(parent_id):
if parent_id not in children_map:
return []
return [
{
**cat.to_json(),
"children": dfs(cat.id)
}
for cat in children_map[parent_id]
]
# Top level categories exist in the None bucket
return dfs(None)
Trees
Triangles
No comments on this post yet. Be the first to share your wisdom :)