JavaScript is required

Using React

This guide is the React-specific quick start for relation-graph, based on ai-prompts/relation-graph-guide.md.

1. Install

npm install --save @relation-graph/react

Legacy package name relation-graph-react is still usable, but @relation-graph/react is the recommended package name.

2. Core Components You Will Use

  • RGProvider: provides graph context (instance + reactive state) to inner components.
  • RelationGraph: renders the graph view.
  • RGHooks: access graph instance/state in React components.

3. Minimal React Setup

import React, { useEffect } from 'react';
import { RGProvider, RelationGraph, RGHooks } from '@relation-graph/react';
import type { JsonNode, JsonLine, RGOptions } from '@relation-graph/react';

const GraphView: React.FC = () => {
  const graphInstance = RGHooks.useGraphInstance();

  const graphOptions: RGOptions = {
    showToolBar: false,
    wheelEventAction: 'scroll',
    dragEventAction: 'move',
    layout: {
      layoutName: 'tree',
      from: 'left',
      treeNodeGapH: 150,
      treeNodeGapV: 10
    }
  };

  const initializeGraph = async () => {
    const nodes: JsonNode[] = [
      { id: '1', text: 'Root' },
      { id: '2', text: 'React App' },
      { id: '3', text: 'Graph Engine' },
      { id: '4', text: 'API Layer' }
    ];
    const lines: JsonLine[] = [
      { from: '1', to: '2', text: 'uses' },
      { from: '1', to: '3', text: 'drives' },
      { from: '2', to: '4', text: 'calls' }
    ];

    graphInstance.clearGraph();
    graphInstance.addNodes(nodes);
    graphInstance.addLines(lines);

    // If node width/height are not preset, wait for node size measurement before layout.
    setTimeout(() => {
      const layouter = graphInstance.createLayout({
        layoutName: 'tree',
        from: 'left',
        treeNodeGapH: 150,
        treeNodeGapV: 10
      });
      const allNodes = graphInstance.getNodes();
      const rootNode = graphInstance.getNodeById('1');
      if (rootNode) {
        layouter.placeNodes(allNodes, rootNode);
      }
      graphInstance.moveToCenter();
      graphInstance.zoomToFit();
    }, 300);
  };

  useEffect(() => {
    initializeGraph();
  }, []);

  return (
    <div style={{ width: '100vw', height: '100vh', backgroundColor: '#ffffff' }}>
      <RelationGraph options={graphOptions} />
    </div>
  );
};

const MyGraphPage: React.FC = () => {
  return (
    <RGProvider>
      <GraphView />
    </RGProvider>
  );
};

export default MyGraphPage;

4. Data Input Strategies

relation-graph supports three common data input patterns in React:

  1. addNodes + addLines + custom layout (best for dynamic and fine-grained updates).
  2. setJsonData one-shot initialization (convenient for loading a complete graph at once).
  3. initialData prop (useful for initial/SSR-friendly rendering).

4.1 One-shot with setJsonData

const initializeGraph = () => {
  const nodes: JsonNode[] = [
    { id: '1', text: 'Root' },
    { id: '2', text: 'A' },
    { id: '3', text: 'B' }
  ];
  const lines: JsonLine[] = [
    { from: '1', to: '2' },
    { from: '1', to: '3' }
  ];

  graphInstance.setJsonData({
    rootId: '1',
    nodes,
    lines
  });
};

setJsonData internally handles clear/add/layout/center/zoom flow, so it is very fast for initial full-graph display.

4.2 Initial data via initialData

<RelationGraph
  options={graphOptions}
  initialData={{
    rootId: '1',
    nodes,
    lines
  }}
/>

5. Register Interaction Events

import type { RGNode, RGLine, RGLink, RGUserEvent } from '@relation-graph/react';

const onNodeClick = (nodeObject: RGNode, event: RGUserEvent) => {
  console.log('node click:', nodeObject.id, event);
};

const onLineClick = (lineObject: RGLine, linkObject: RGLink, event: RGUserEvent) => {
  console.log('line click:', lineObject.from, lineObject.to, linkObject, event);
};

<RelationGraph
  options={graphOptions}
  onNodeClick={onNodeClick}
  onLineClick={onLineClick}
/>

6. Access Graph State with RGHooks

RGHooks provides reactive state objects from graph runtime:

const graphInstance = RGHooks.useGraphInstance();
const creatingLine = RGHooks.useCreatingLine();
const creatingNode = RGHooks.useCreatingNode();
const editingNodes = RGHooks.useEditingNodes();
const editingLine = RGHooks.useEditingLine();
const connectingNode = RGHooks.useConnectingNode();
const viewInformation = RGHooks.useViewInformation();
const selectionView = RGHooks.useSelectionView();
const checkedItem = RGHooks.useCheckedItem();

This makes it straightforward to build custom toolbars, inspectors, and editor side panels that stay in sync with graph interactions.

7. Practical Notes

  • The size of <RelationGraph> is determined by its parent container size.
  • options is initial config; if you need runtime updates, call instance APIs such as graphInstance.updateOptions(...).
  • If <RelationGraph> unmounts while <RGProvider> stays mounted, clear old data before loading new graph data (graphInstance.clearGraph()).
  • For dynamic editors, prefer granular APIs (addNodes, addLines, update/remove methods) over repeated setJsonData to avoid visible re-centering jitter.

8. Next Reading