How Can I Make A Dynamic Tree Component?
Hi, I would like to generate a specific html structure for a binary tree given a JSON in input.
Hopefully I can explain the requirement well enough.
Each node of my tree is either an Expression or a Literal.
- Each Expression has a left and right child node and an operator
- Each Literal has a value
When I'm drawing my tree I want to do the following:
- If the node is an Expression check the two children then return
<div>{LEFT} {operator} {RIGHT}</div>
.
- If either of the children is a Literal then LEFT/RIGHT will just print the value.
- If either of the children is an Expression then LEFT/RIGHT will have a button
- Pressing the button should expand a div below the button containing the same structure but for the children expression.
Hopefully the attached image will help understanding.
Here is also a codepen when I tried doing an implementation: https://codepen.io/thevinter/pen/ByavwvM
However I am not able to expand the element properly on the edges. The idea is to make the container scrollable and expanding to the left/right when needed.
Could someone help?
6 Replies
up!
Given how things align, could you figure out how many grid columns you need & position the elements within that?
I was screwing around with the code contemplating how to do this, but unfortunately ran out of time. What's there may help you clean up your code a bit.
¿You don't know any Svelte, do you? This would be about 30⨯ easier to write in Svelte. 😸
I'm not sure to understand what you want to do. From what you explained it looks like you want to make a display that can show mathematical expression as an abstract syntax tree where each element of the expression is either a value ("Literal" in your explanation) or an operand ("Expression" in your explanation). And you want to show that syntax tree initially collapsed with the possibility of opening the left and right branch of operands if there's any.
(I'm not sure what the "Property" type you have in your code is supposed to be)
If I understand correctly you can't get the display of you tree to line up when you open your "Expressions", is that correct ?
from the screenshot you provided I'm not sure if you want the expression to expend (replacing a placeholder with the expression when you click it and showing on a new line) as the first 3 lines suggest or if you want if you just want to display the tree structure of the expression like in the diagram bellow it
Sorry, ignore the Property type, slipped in but its not really relevant for the topic at hand
I want to display it in a tree structure like in the diagram
i.e. the user should see "X + <button>" at first, and then they can click the button to expand the inner expression

and so on
To reply to this. I am using react, so doing parts of it in js is not an issue. I thought of preemptively building a grid with the divs, but I am not sure how optmized that would be considering it might end up being very sparse