Skip to content

Instantly share code, notes, and snippets.

@joemaffei
Created November 10, 2023 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemaffei/5740765aef7f066c3f1ea45f0941ee42 to your computer and use it in GitHub Desktop.
Save joemaffei/5740765aef7f066c3f1ea45f0941ee42 to your computer and use it in GitHub Desktop.
Simple FileTree component
const FileTreeStyles = styled.ul`
button {
font-family: monospace;
background: none;
border: 0;
padding: 0.125em 0;
&:hover {
background: #f002;
}
}
`;
function FileTree({ rootNode, root = true, onClick }) {
const [showChildren, setShowChildren] = useState(false);
const RootNode = root ? FileTreeStyles : Fragment;
return (
<RootNode>
<li>
<button
type="button"
className="file-tree"
onClick={() => setShowChildren((current) => !current)}
>
{showChildren ? "▼" : "▶️"} {rootNode.name}
</button>
</li>
{showChildren && (
<ul style={{ paddingLeft: "1em" }}>
{rootNode.children.map((childNode) => {
if (childNode.children) {
return <FileTree rootNode={childNode} root={false} onClick={onClick} />;
}
return (
<li>
<button type="button" onClick={() => onClick(childNode)}>
📄 {childNode.name}
</button>
</li>
);
})}
</ul>
)}
</RootNode>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment