Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simplest tree view rendering in react
import React from 'react';
function shortId() {
// Taken from stackoverflow. I Forget the reference.
// I generate the UID from two parts here
// to ensure the random number provide enough bits.
var firstPart = (Math.random() * 46656) | 0;
var secondPart = (Math.random() * 46656) | 0;
firstPart = ("000" + firstPart.toString(36)).slice(-3);
secondPart = ("000" + secondPart.toString(36)).slice(-3);
return firstPart + secondPart;
}
const data = [
{
name: 'Imgsquash',
link: null,
children: [
{name: '1.png', link: 'http://example.com' },
{name: '2.png', link: 'http://example.com' },
{name: 'unsplash', children: [
{ name: 'un-1.jpeg'},
{ name: 'un-2.jpeg'}
] }
],
}
]
class TreeView extends React.Component {
renderView = (nodes) => {
return nodes.map(item => {
return (<ul key={shortId()}>
<li>
<h6>{item.name}</h6>
{(typeof(item.children) !== 'undefined') ? this.renderView(item.children) : ''}
</li>
</ul>)
})
}
render() {
return this.renderView(data)
}
}
export default TreeView;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.