react-collapsible-tree

2.0.0 • Public • Published

react-collapsible-tree

Creates a React Tree View from JSON Data.
Displays a Folder Open Icon and Folder Normal Icon according to state, as well as a File Icon.
For full explanation, look at the example in examples/normal-tree.

Install:

npm install react-collapsible-tree

or

yarn add react-collapsible-tree

How To Use

The tree uses a flat structure, which contains items in the following structure:

"1": {
  "id": "1",
  "name": "Item-1",
  "parentid": null, // parentid for subfolders 
  "children": null
}

Example input.json:

{
  "items": {
    "0": {
      "id": "0",
      "name": "Item-1"
    },
    "1": {
      "id": "1",
      "name": "Item-1",
      "children": ["1-1", "1-2", "1-3"]
    },
    "1-1": {
      "id": "1-1",
      "name": "Item-1-1",
      "children": null
    },
    "1-2": {
      "id": "1-2",
      "name": "Item-1-2",
      "children": null
    },
    "1-3": {
      "id": "1-3",
      "name": "Item-1-3",
      "children": null
    }
  },
  "topIds": [0,1]
}

Render component:

<Tree
    items={this.state.items} // items 
    topIds={this.state.topIds} // array containing all top level item ids
    onSelection={this.onSelection} // function 
    selection={0} // selection
    parentIcon={undefined} // icon for folder
    parentOpenIcon={undefined} // icon for folder open
    leafIcon={undefined} // icon for single file
/>

don't forget the topIds prop, it tells the component which items to render at the top level


Implement onSelection:

first import TreeUtils

import { TreeUtils } from 'react-collapsible-tree'

then add the method:

onSelection = id => {
  this.setState(state => ({
    selected: id,
    items: TreeUtils.toggleItemsToId(state.items, id, state.selected)
  }))
}

TreeUtils.toggleItemsToId finds the passed in node of the tree by id. Then it adds an attribute showChildren: true to all parents of that node. The Tree component updates itself accordingly after the new state was passed in.

Styling

For best styling using CSS, react-collapsible-tree adds some CSS Classes:

  • react-collapsible-tree-container - outer container
  • react-collapsible-tree-node - a tree node
  • react-collapsible-tree-node-selected - a selected tree node

Package Sidebar

Install

npm i react-collapsible-tree

Weekly Downloads

2

Version

2.0.0

License

MIT

Unpacked Size

72.3 kB

Total Files

6

Last publish

Collaborators

  • philippczernitzki