JSPM

  • Created
  • Published
  • Downloads 10
  • Score
    100M100P100Q47571F
  • License MIT

A tree component with collapsible nodes

Package Exports

  • react-collapsible-tree

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-collapsible-tree) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

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