React ApexTree

Installation

npm install react-apextree apextree

Note: apextree is a peer dependency and must be installed alongside react-apextree.

Demo

View Demo Project created using react-apextree

Basic Usage

import { ApexTreeChart, type TreeOptions } from "react-apextree";

const data = {
  id: "1",
  name: "CEO",
  children: [
    {
      id: "2",
      name: "CTO",
      children: [
        { id: "3", name: "Dev Lead" },
        { id: "4", name: "QA Lead" },
      ],
    },
    {
      id: "5",
      name: "CFO",
    },
  ],
};

// keep options referentially stable: a new object rebuilds the tree
const options: Partial<TreeOptions> = {
  width: 800,
  height: 600,
  direction: "top",
  nodeWidth: 120,
  nodeHeight: 80,
};

function App() {
  return <ApexTreeChart data={data} options={options} />;
}

Setting License Key

If you have a commercial license, set it once at app initialization:

import { setApexTreeLicense } from 'react-apextree';

// call at app initialization before rendering any charts
setApexTreeLicense('your-license-key-here');

Using Imperative Methods

Access methods like changeLayout, collapse, expand, and fitScreen via ref:

import { useRef } from "react";
import { ApexTreeChart, ApexTreeRef } from "react-apextree";

const options = { width: 800, height: 600 };

function App() {
  const treeRef = useRef<ApexTreeRef>(null);

  const handleChangeLayout = () => {
    treeRef.current?.changeLayout("left");
  };

  const handleCollapse = (nodeId: string) => {
    treeRef.current?.collapse(nodeId);
  };

  const handleExpand = (nodeId: string) => {
    treeRef.current?.expand(nodeId);
  };

  const handleFitScreen = () => {
    treeRef.current?.fitScreen();
  };

  return (
    <div>
      <button onClick={handleChangeLayout}>Change Layout</button>
      <button onClick={handleFitScreen}>Fit Screen</button>

      <ApexTreeChart ref={treeRef} data={data} options={options} />
    </div>
  );
}

Custom Node Templates

const options = {
  width: 800,
  height: 600,
  contentKey: "data",
  nodeWidth: 150,
  nodeHeight: 100,
  nodeTemplate: (content) => `
    <div style="display: flex; flex-direction: column; align-items: center; height: 100%;">
      <img 
        src="${content.imageURL}" 
        style="width: 50px; height: 50px; border-radius: 50%;" 
      />
      <div style="font-weight: bold;">${content.name}</div>
    </div>
  `,
};

<ApexTreeChart data={data} options={options} />

Props

PropTypeDescription
dataNestedNodeTree data structure (required)
optionsEvery core apextree option: size, direction, node and edge styling, templates, toolbar, tooltip, theme and the rest
onNodeClick(node: unknown) => voidNode click handler
classNamestringCSS class for the container
styleCSSPropertiesInline styles for the container

Layout and styling go in options, not as separate props. See Options for every key and its default. Keep options referentially stable; see Updating data.

Updating data

A change to the data prop is reconciled into the live tree rather than rebuilding it. Surviving nodes spring to their new positions, new ids grow in, and departed ones retract, while collapse state, selection, focus and expanded cards all survive.

const [org, setOrg] = useState(initialOrg)

// animates into the new shape; does not tear the chart down
useEffect(() => {
  socket.on('org:changed', setOrg)
}, [])

return <ApexTreeChart data={org} options={options} />

A change to the options prop rebuilds the instance, since options are read at construction. Keep options referentially stable (a module constant, or useMemo) so an unrelated re-render does not remount the chart.

See Live Data Updates.

Ref Methods

MethodDescription
changeLayout(direction?)Change tree direction
collapse(nodeId)Collapse a node
expand(nodeId)Expand a node
expandAll()Expand every node in one reflow
collapseAll()Collapse every node, leaving the root visible
expandToDepth(depth)Show the tree down to a depth (root = 0)
updateData(data)Diff against a new dataset and spring to it
focus(nodeId)Spotlight a node's lineage and subtree
clearFocus()Remove the spotlight
setActivePath(nodeIds)Flow a marching dash along the root-to-node path
clearActivePath()Clear the active-path flow
toggleCard(nodeId)Toggle a node's expanded card
zoom(factor)Zoom by a fraction of the current scale (positive in, negative out)
centerOnNode(nodeId)Center the camera on a node
fitScreen()Fit tree to screen
refreshTokens()Re-read the tree's CSS variables, the family tokens, the registered theme and the Ignite UI theme, and repaint (apextree 2.3.0 or later)
getGraph()Get the underlying graph instance for the full API

getGraph() returns the core Graph, so anything not on the ref handle (expandSubtree, getExpandedCards, getActivePath, exportToSvg, selection and search) is reachable through it. See Methods.

Theming and Ignite UI

options is typed off the core apextree package you have installed, so with apextree 2.3.0 it takes theme, tokens and designSystem as well as every color option. An option you pass beats the --apex-tree-* CSS variables and the --apx-* tokens, so leave out any option a stylesheet should drive. See Theming and Customization.

To follow an Ignite UI theme on the page, import the add-on once, anywhere in your app, before the first tree renders. It ships in the core apextree package and needs no extra licence key:

import 'apextree/ignite-ui'

// per tree: designSystem: false ignores the Ignite UI theme, tokens: false ignores every token.
// Declare the options at module scope so a re-render does not rebuild the tree.
const noIgnite = { designSystem: false }

<ApexTreeChart data={data} options={noIgnite} />

The tree reads its theme when it renders. When the theme changes without a prop change, for example after a stylesheet swap for an Ignite UI light/dark switch, a class toggle that sets the variables, or the add-on loading after the first render, call refreshTokens() on the ref. Nodes, expanded cards, selection, focus and the active path are kept:

const treeRef = useRef<ApexTreeRef>(null)

themeLink.onload = () => treeRef.current?.refreshTokens()

refreshTokens() needs react-apextree 2.2.0 and apextree 2.3.0; on an older core it does nothing. See Using with Ignite UI.

Data Structure

interface NodeData<T = unknown> {
  id: string; // unique identifier
  name?: string; // display name (or use contentKey)
  data?: T; // custom data for templates
  options?: NodeOptions; // per-node styling
  children?: NodeData<T>[];
}

interface NodeOptions {
  nodeBGColor?: string;
  nodeBGColorHover?: string;
  borderColor?: string;
  borderColorHover?: string;
  fontSize?: string;
  fontFamily?: string;
  fontWeight?: string | number;
  fontColor?: string;
}

TypeScript Support

Full TypeScript support with exported types:

import type {
  ApexTreeProps,
  ApexTreeRef,
  NodeData,
  NodeOptions,
  TreeDirection,
  GraphInstance,
} from "react-apextree";

GitHub