Simple Tree View Component In Vanilla JavaScript

Category: Javascript | August 16, 2021
Author:petrbroz
Views Total:1,181 views
Official Page:Go to website
Last Update:August 16, 2021
License:MIT

Preview:

Simple Tree View Component In Vanilla JavaScript

Description:

A simple vanilla JavaScript tree view component that can be used to visualize any hierarchical data like files and folders.

How to use it:

1. Install and import the VanillaTreeView component with NPM.

# NPM
$ npm i simple-treeview --save
import { VanillaTreeView } from './dist/treeview.vanilla.js';
<link rel="stylesheet" href="./dist/treeview.vanilla.css" />

2. It also comes with a Bootstrap version that is compatible with the latest Bootstrap 5 framework.

import { BootstrapTreeView } from './dist/treeview.bootstrap.js';
<link rel="stylesheet" href="./dist/treeview.bootstrap.css" />

3. Create an empty DIV container that will host the tree view.

<div id="tree"></div>

4. The code below shows how to present data in the tree view. It is important to note that the component makes use of Font Awesome icons (Bootstrap Icons for Bootstrap version), so classes such as `fa-folder` or `fa-clock` can be used in {@link INode}'s `icon` property.

let tree = new VanillaTreeView(document.getElementById('tree'), {
    provider: {
        async getChildren(id) {
            if (!id) {
                return [
                    { id: 'p1', label: 'Parent #1', icon: 'fa-folder', state: 'collapsed' },
                    { id: 'p2', label: 'Parent #2', icon: 'fa-folder', state: 'expanded' }
                ];
            } else {
                await new Promise((resolve, reject) => setTimeout(resolve, 1000));
                switch (id) {
                    case 'p1':
                        return [
                            { id: 'c1', label: 'Child #1', icon: 'fa-file', state: 'collapsed' },
                            { id: 'c2', label: 'Child #2', icon: 'fa-file' }
                        ];
                    case 'p2':
                        return [
                            { id: 'c3', label: 'Child #3', icon: 'fa-file' },
                            { id: 'c4', label: 'Child #4', icon: 'fa-file' }
                        ];
                    case 'c1':
                        return [
                            { id: 'g1', label: 'Grandchild #1', icon: 'fa-clock' }
                        ];
                    default:
                        return [];
                }
            }
        }
    }
});

You Might Be Interested In:


Leave a Reply