React: Parse a nested object to make a menu
React: Parse a nested object to make a menu
by lshettyl
HTML
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>
Babel + JSX
const data = [{
"title": "Food",
"path": "/root",
"children": [{
"title": "Veg",
"path": "/root/Food",
"children": [{
"title": "Carrot",
"path": "/root/Food/Veg",
"children": [{
"title": "Ooty carrot",
"path": "/root/Food/Veg/Brinjal",
"children": []
}]
}]
}]
}, {
"title": "Cloths",
"path": "/root",
"children": [{
"title": "T shirt",
"path": "/root/Cloths",
"children": []
}, {
"title": "Shirt",
"path": "/root/Cloths",
"children": []
}]
}]
const MyComponent = ({
data
}) => {
return ( <
ol >
{
data.map((m, index) => {
return ( < li key = {
index
} > {
m.title
} {
m.children && < MyComponent data = {
m.children
}
/>} <
/li>);
})
}
<
/ol>
);
}
class App extends React.Component {
render() {
return <div >
<
MyComponent data = {
data
}
/> <
/div>
}
}
ReactDOM.render( < App / > , document.getElementById('root'));