How to create a multilevel list?

  • 0
    I have 2 JSON files like this:
    https://yadi.sk/d/k9GCcUo72cfRvg?w=1

    How can I do it correctly so that it ends up like this:


    My current solution looks, in my opinion, not very universal, since everything will break with the growth of nesting:

    class Sections extends React.Component {
    
        handleAddEvent = () => (childrensCount, id) => {
            const { products } = this.props;
            if (childrensCount === 0) {
                console.log(products.filter( (elem) => {
                    return elem.parent_section === id
                }))
            }
        }
    
    
    
        render () {
    
            const { sections, products } = this.props;
    
            const highLvl = sections.filter((item) => {
                return item.parent === 0
            })
    
            console.log('products', products);
    
            return (
                <div>
                    {highLvl.map((section) => {
    
                        const childrensCount = sections.reduce((acc, elem) => {
                        const isChildren = elem.parent === section.id? 1 : 0;
                        return acc + isChildren 
                        }, 0);
    
                        console.log('Section ' + section.name + ' имеет детей: ' + childrensCount);
    
                        return (
                            <div onClick={this.handleAddEvent(childrensCount, section.id)}>{section.name}</div>
                        );
                    })}
                </div>
            );
        }
    }


    Perhaps it is worth using recursion, but it’s very hard for me, I can understand it by example, but I cannot implement it myself.

    The point here is that if this is the lowest level, then by clicking on it, the products themselves will be displayed, and if not, then the list will expand, as in the picture.
    JavaScript Anonymous, Apr 8, 2019

  • 0 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!