1

I am new to react, I have tried to create a nested tree of folders and files of recursion. I have created 03 components Tree, Folder, and File. In the tree I have put the logic of recursion I map all the elements if I find a folder I create the folder and recall the function if I find a file I display it directly (see code below).

The function creates the level 0 elements only. I wonder why once I recall again the function Tree <Tree tree ={item.items}/> inside the folder it does function. Any hint?

export function Tree ({tree})  {
const items = tree
  return (
   <>
    {items.map((item, idx) => { 
            if (item.items) {
                /**
                 * is Folder
                 */
                return (
                    <Folder key={idx} folder_name={item.name} num_folders={items.length} >
                        {<Tree tree ={item.items}/> /**this does not work**/}
                    </Folder>
                )
            }
            else {
                return (
                <File key={idx} file_name= {item.name} file_icon={item.icon} file_size ={item.size} />
                ) 
            }
        })}
   </>
  );
}
DINA TAKLIT
  • 7,074
  • 10
  • 69
  • 74
  • check if this is helpful https://stackoverflow.com/questions/28205317/how-to-render-child-components-in-react-js-recursively – Bugfixer Mar 22 '21 at 18:10
  • I have tried to create them within a function that I will call in the render method but does not work too – DINA TAKLIT Mar 22 '21 at 18:14

1 Answers1

1

You should use React children property.

children is a special property of React components which contains any child elements defined within the component, e.g. the divs inside Example above. {this.props.children} includes those children in the rendered result.

So what u insert inside the <Folder> </Folder> will be rendered via children property. Just update your folder components to render those children items like this:

export function Folder({ other_props, children}){
    ...
    return (
        <div>
            ... 
            {
                children 
            }    
        </div>
    );
}

Read more about children property in this stack question What is {this.props.children} and when you should use it?

Ahmad Alsabbagh
  • 291
  • 3
  • 6