'Add children to a react component following depth-first traversal
How can you append children to already declared React elements?
const MyElement = <SomeComponent/>;
MyElement.append(<SomeChild />);
MyElement.append(<AnotherChild />);
An example:
Let's say you're trying to render a 'tree' list, for example a file-navigation where you have an arbitrary number of sub-lists.
Now if you want to this in a depth-first manner, you need a reference to existing nodes, and be able to append children to them.
Example data structure:
Let's assume a bunch of nested Maps here. Each key is a file or folder. Their value is a map of their children.
{
[Folder_1] => {
[Folder_1.1] => {
[File_1.1.1] => null
}
[Folder_1.2] => {
[Folder_1.2.1] => {
[File_1.2.1.1] => null
}
[File_1.2.2] => null
}
}
}
Now the React output we want is this:
<FileNavigator>
<Node node={Folder_1}>
<Node node={Folder_1.1}>
<Node node={File_1.1.1}>
</Node>
</Node>
<Node node={Folder_1.2}>
<Node node={Folder_1.2.1}>
<Node node={File_1.2.1.1}>
</Node>
<Node node={File_1.2.2}>
</Node>
</FileNavigator>
Note on existing SO answers:
- How to append child to React element?: The answers in this one focus on React.createElement letting you pass a 'children' prop. React.createElement doesn't work for 'depth-first' additions, since it assumes you know all the children at the time the method is called.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
