Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-arborist

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-arborist

A full-featured tree component for React.

  • 0.1.11
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

React Arborist

A full-featured tree component for React.

The tree UI is ubiquitous in software applications. There are many tree component libraries for React, but none were full-featured enough to stand on their own.

This library provides all the common features expected in a tree. You can select one or many nodes to drag and drop into new positions, open and close folders, render an inline form for renaming, efficiently show thousands of items, and provide your own node renderer to control the style.

Demo

Installation

yarn add react-arborist
npm install react-arborist

Example

Render the tree data structure.

const data = {
  id: "The Root",
  children: [{id: "Node A"}, {id: "Node B"}]
}

function App() {
  return (
    <Tree data={data}>
      {Node}
    </Tree>
  );
}

function Node({ ref, styles, data}) {
  return (
    <div ref={ref} style={styles.row}>
      <div style={styles.indent}>
        {data.name}
      </div>
    </div>
  )
}
Contents
  • Expected Data Structure
  • Tree Component API
  • Node Renderer API

Expected Data Structure

The Tree component expects the data prop to be a tree-like data structure with the following type:

type Data = {
  id: string, /* Required */
  children?: Data[]
  isOpen?: boolean
}

If your data does not look like this, you can provide a childrenAccessor prop. You can also provide isOpenAccessor. The value can be a string or a function.

<Tree childrenAccessor="items" ... 
// Or 
<Tree childrenAccessor={(node) => node.items} ... 

Tree Component

Unlike other Tree Components, react-arborist is designed as a controlled component. This means the consumer will provide the tree data and the handlers to update it. The only state managed internally is for drag and drop, selection, and editing.

PropDefaultDescription
data(required)The tree data structure to render as described above.
width300The width of the tree.
height500The height of the tree. To dynamically fill it's container, use a hook or component to gather the width and height of the Tree's parent.
rowHeight24The height of each row.
indent24The number of pixels to indent child nodes.
hideRootfalseHide the root node so that the first set of children appear as the roots.
onTogglenoopHandler called when a node is opened or closed. This and the subsequent functions should update the data prop for the tree to re-render.
onMovenoopHandler called when a user moves one or more nodes by dragging and dropping.
onEditnoopHandler called when a user performs an inline edit of the node.
childrenAccessor"children"Used to get a node's children if they exist on a property other than "children".
isOpenAccessor"isOpen"Used to get a node's openness state if it exists on a property other than "isOpen".
openByDefaulttrueChoose if the node should be open or closed when it has an undefined openness state.
classNameundefinedAdds a class to the containing div.

The only child of the Tree Component must be a NodeRenderer function as described below.

const NodeRenderer = ({
  innerRef, data, styles, handlers, state, tree
}) => ...

const MyApp = () => 
  <Tree>
    {NodeRenderer}
  </Tree>

Node Renderer Component

The Node Renderer is where you get to make the tree your own. You completely own the style and functionality. The props passed to it should enable you to do whatever you need.

The most basic node renderer will look like this:

function NodeRenderer({
  innerRef, 
  styles, 
  data, 
  state, 
  handlers, 
  tree
}) {
  return (
    <div ref={innerRef} style={styles.row}>
      <div style={styles.indent}>{data.id}</div>
    </div>
  )
}

The function above is passed data for this individual node, the DOM ref used for drag and drop, the styles to position the row in the virtualized list and the styles to indent the current node according to its level in the tree.

PropTypeDescription
dataNodeA single node from the tree data structure provided.
innerRefRefMust be attached to the root element returned by the NodeRenderer. This is needed for drag and drop to work.
stylesobjectThis is an object that contains styles for the position of the row, and the level of indentation. Each key is described below.
stateobjectAn handful of boolean values that indicate the current state of this node. See below for details.
handlersobjectA collection of handlers to attach to the DOM, that provide selectable and toggle-able behaviors. Each handler is described below.
treeTreeMonitorThis object can be used to get at the internal state of the whole tree component. For example, tree.getSelectedNodes(). All the methods are listed below in the Tree Prop section.

Styles Prop

These are the properties on the styles object passed to the NodeRenderer.

NameTypeDescription
rowCSSPropertiesSince the tree only renders the rows that are currently visible, all the rows are absolutely positioned with a fixed top and left. Those styles are in this property.
indentCSSPropertiesThis is simply a left padding set to the level of the tree multiplied by the tree indent prop.

State Prop

These are the properties on the state object passed to the NodeRenderer.

NameTypeDescription
isOpenbooleanTrue if this node has children and the children are visible. Use this to display some type a open or closed icon.
isSelectedbooleanTrue if this node is selected. Use this to show a "selected" state. Maybe a different background?
isHoveringOverChildbooleanTrue if the user is dragging n node, and the node is hovering over one of this node's direct children. This can be used to indicate which folder the user is dragging an item into.
isDraggingbooleanTrue if this node is being dragged.
isFirstOfSelectedbooleanTrue if this is the first of a contiguous group of selected rows. This can be used to tastefully style a group of selected items. Maybe a different border radius on the first and last rows?
isLastOfSelectedbooleanTrue if this is the last of a contiguous group of selected rows.
isEditingbooleanTrue if this row is being edited. When true, the renderer should return some type of form input.

Handlers Prop

These are the properties on the handlers object passed to the NodeRenderer.

NameTypeDescription
selectMouseEventHandlerAttach this to the element that tiggers selection. Maybe you want to add it to the outermost div.
<div onClick={handlers.select}>
toggleMouseEventHandlerAttach this to the element that opens and closes the node. Maybe you want to add it to the +/- icon.
<icon onClick={handlers.toggle}>
edit() => voidMakes this node editable. This will re-render the Node with the state.isEditing prop set to true.
submit(update: string) => voidSends the update to the onEdit handler in the Tree component, and sets the state.isEditing prop to false.
reset() => voidRe-renders with the state.isEditing prop set to false.

Tree Prop

The tree monitor provides methods to get the tree's internal state. A use case might be in a right click menu.

// In your node renderer
onContextMenu={() => {
  // Do something with all the selected nodes
  tree.getSelectedIds()
}}
MethodsReturnsDescription
getSelectedIds()string[]Get the the ids of all currently selected nodes.
edit(id: string)voidEdit a node programatically.

FAQs

Package last updated on 29 Oct 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc