Facebook Pixel

How do you render a tree structure recursively in JavaScript?

Write a function that creates a DOM element for the current node, then recursively calls itself for each child. Append the children to a container. For folders, add a click handler to toggle the children's visibility.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How to Build a File Explorer in an Interview

Use a tree data structure (objects with name, type, children). Write a recursive function to render each node. Folders have a click handler to expand/collapse children. Use indentation based on depth and icons for files/folders.

A tree structure: each node is an object with name, type (file or folder), and children (array of child nodes, only for folders). Files have no children. Folders can have nested folders and files.

Add a click handler to folder elements. Toggle the display of the children container (display: none or block). Update the folder icon (open/closed). Use stopPropagation to prevent parent folders from toggling when a child is clicked.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.