Skip to content

Example · React

React Network Graph

A drop-in React component that renders an interactive force-directed network graph. Pan, zoom, drag nodes, and respond to hover and click — all included. Works in any React 18+ application (CRA, Vite, Next.js, Remix, React Router).

1. Install

terminal
npm install @topokit/react

2. Drop in the component

NetworkGraph.tsx
import { GraphCanvas } from '@topokit/react';
import type { Node, Edge } from '@topokit/core';

const nodes: Node[] = [
  { id: 'a', label: 'Alice', data: { role: 'admin' } },
  { id: 'b', label: 'Bob', data: { role: 'editor' } },
  { id: 'c', label: 'Carol', data: { role: 'viewer' } },
];

const edges: Edge[] = [
  { id: 'e1', source: 'a', target: 'b' },
  { id: 'e2', source: 'b', target: 'c' },
  { id: 'e3', source: 'a', target: 'c' },
];

export function NetworkGraph() {
  return (
    <GraphCanvas
      nodes={nodes}
      edges={edges}
      layout="force"
      theme="dark"
      interactive
      style={{ width: '100%', height: '600px' }}
      onNodeClick={(node) => console.log('clicked', node)}
      onNodeHover={(node) => console.log('hover', node?.id)}
    />
  );
}

3. (Optional) Drive it from a hook

The useGraph hook gives you the underlying graph instance for batch updates, layout swaps, and search.

DynamicNetworkGraph.tsx
import { GraphCanvas, useGraph } from '@topokit/react';

export function DynamicNetworkGraph() {
  const { graph, app } = useGraph({
    nodes: [],
    edges: [],
    layout: 'force',
  });

  const addNode = () => {
    graph.batch(() => {
      const id = `n-${Date.now()}`;
      graph.addNode({ id, label: id });
    });
  };

  return (
    <>
      <button onClick={addNode}>Add node</button>
      <GraphCanvas app={app} style={{ width: '100%', height: '600px' }} />
    </>
  );
}