Skip to content

Instantly share code, notes, and snippets.

@eashish93
Created January 25, 2018 07:01
Show Gist options
  • Save eashish93/14a7e2d55840b6c5b2f30b116677a97a to your computer and use it in GitHub Desktop.
Save eashish93/14a7e2d55840b6c5b2f30b116677a97a to your computer and use it in GitHub Desktop.
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