Today after watching a getting started course about React, I tried to code my very first React component, a "treeview" as the title says. It does work, but as a newbie I know there are many improvement that can be done.
It receives a data array like the one below:
[{
descp: 'UNE',
url: '/tree/une',
icon: 'icon-list',
children: [
{
descp: 'ATI',
url: '/tree/une/ati',
icon: 'icon-layers',
children: [{
descp: 'ATI-VC',
url: '/tree/une/ati/ativc',
icon: 'icon-pin',
children: []
},
{
descp: 'ATI-CMG',
url: '/tree/une/ati/aticmg',
icon: 'icon-pin',
children: []
}
]
},
{
descp: 'EMGEF',
url: '/tree/une/emgef',
icon: 'icon-layers',
children: []
},
{
descp: 'ECIE',
url: '/tree/une/ecie',
icon: 'icon-layers',
children: []
},
{
descp: 'GEYSEL',
url: '/tree/une/geysel',
icon: 'icon-layers',
children: []
}
]
}]
Maybe the data format can be improve as well but the real deal is the component:
const MyTree = (props) => {
const { list } = props;
return (
list.map((child,i)=>
<MyTreeNestedItems key={i} data={child} />
)
);
};
const MyTreeNestedItems = (props) => {
const { data } = props;
const createChildren = (list) => {
return (
list.map((child,i)=>
<MyTreeNestedItems key={i} data={child} />
)
)
}
let children = null;
if (data.children.length) {
children = createChildren(data.children);
}
return (
<li className="nav-item">
<a className="nav-link" href="#">
<span className={data.icon}></span> {" "}
{ data.descp }
</a>
<ul style={{listStyleType:"none"}}>{children}</ul>
</li>
);
};
render(<MyTree list={tree} />,document.querySelector('.js-mytree'));
Any tips would be gratefully appreciated.