Skip to content
D
Documentation

React: state and content

how-to
6 min readUpdated

Use controlled state when another part of your app needs the graph, and React components when you need to paint node or widget interiors. You get a canvas whose edits return to React state, sibling panels that follow the live instance, and an SVG that can render before client hydration.

Start in the Vite TypeScript project from the React quick start. Its binding and peer packages are already installed; these examples add no dependencies. Keep src/main.tsx, its StrictMode wrapper and stylesheet imports. Each example below is a separate component you can render from the existing App.

1. Close the controlled-state loop

GrafloriaFlow converts your specs into live models. useNodesState and useEdgesState provide the return path: the third tuple element converts the models received by the change callback back into specs.

For graph input types, see Instance and lifecycle. This example renders Build and Deploy inside a Pipeline zone. Dragging a card commits its new position back to React state.

The custom card receives NodeProps: id, your data, live selected state, and the live node. Render the inside of the box; the engine owns its position, selection and connections. Give the root height: '100%' and boxSizing: 'border-box' to keep it inside the engine-sized host.

tsx
import { useRef, useState } from 'react';
import {
  GrafloriaFlow,
  GrafloriaProvider,
  useEdgesState,
  useNodesState,
} from '@grafloria/react';
import type { NodeProps } from '@grafloria/react';
import type { DiagramInstance, EdgeSpec, GroupSpec, NodeSpec } from '@grafloria/renderer';
import { Inspector } from './Inspector';

type CardData = { title: string; owner: string };

function Card({ id, data, selected, node }: NodeProps<CardData>) {
  return (
    <article
      data-card-id={id}
      style={{
        height: '100%', boxSizing: 'border-box', padding: 14,
        background: '#fff', color: '#172033', borderRadius: 12,
        border: selected ? '2px solid #3b52d9' : '1px solid #94a5f0',
      }}
    >
      <strong>{data.title}</strong>
      <div>Owner: {data.owner}</div>
      <small>{node.type} · {id}</small>
    </article>
  );
}

const initialNodes: NodeSpec[] = [
  {
    id: 'build', type: 'card', custom: true,
    position: { x: 80, y: 90 }, size: { width: 230, height: 110 },
    data: { title: 'Build', owner: 'CI' },
  },
  {
    id: 'deploy', type: 'card', custom: true,
    position: { x: 430, y: 90 }, size: { width: 230, height: 110 },
    data: { title: 'Deploy', owner: 'CD' },
  },
];
const initialEdges: EdgeSpec[] = [
  { id: 'build-deploy', source: 'build', target: 'deploy', label: 'artifact' },
];
const groups: GroupSpec[] = [
  { id: 'pipeline', label: 'Pipeline', children: ['build', 'deploy'], padding: 36 },
];
const nodeTypes = { card: Card };

export function ControlledEditor() {
  const [nodes, , onNodesChange] = useNodesState(initialNodes);
  const [edges, , onEdgesChange] = useEdgesState(initialEdges);
  const instance = useRef<DiagramInstance | null>(null);
  const [message, setMessage] = useState('Mounting canvas');

  return (
    <GrafloriaProvider>
      <section>
        <p role="status">{message}</p>
        <p>{nodes.length} nodes · {edges.length} edges</p>
        <div style={{ display: 'flex', gap: 16 }}>
          <div style={{ flex: 1, minWidth: 0, height: 440 }}>
            <GrafloriaFlow
              nodes={nodes} onNodesChange={onNodesChange}
              edges={edges} onEdgesChange={onEdgesChange}
              groups={groups}
              nodeTypes={nodeTypes}
              className="pipeline-canvas"
              style={{ border: '1px solid #94a5f0' }}
              fitView
              plugins
              highlighterConfig
              highlightConnected
              minZoom={0.2}
              maxZoom={2}
              onInit={(diagram) => {
                instance.current = diagram;
                setMessage('Canvas ready');
              }}
              onNodeClick={({ node }) => setMessage(`Clicked node ${node.id}`)}
              onEdgeClick={({ edge }) => setMessage(`Clicked edge ${edge.id}`)}
              onConnect={({ link }) => setMessage(`Connected ${link.id}`)}
            >
              <button onClick={() => instance.current?.fitView()}>
                Frame pipeline
              </button>
            </GrafloriaFlow>
          </div>
          <Inspector />
        </div>
      </section>
    </GrafloriaProvider>
  );
}

nodeTypes maps type: 'card' to Card; the specs select the HTML path with custom: true. For the rendering-path details, see custom rendering. Ports still belong to the spec, not to elements inside the card; see Arrange ports and connect and the live typed-port example.

Build and Deploy appear inside Pipeline, joined by the artifact edge, with canvas controls and the sibling inspector.

Passing controlled nodes without onNodesChange lets stale state overwrite user edits on the next render. Connect the third element of useNodesState() to onNodesChange, not setNodes: the callback receives live node models, while the setter accepts specs. Use the setter when changing the app's input data; use undoable commands for inspector edits that belong in history.

Keep controlled arrays in state or memoize them. A new nodes, edges or groups reference triggers reconciliation, not a remount. Inline callback functions are safe: the binding keeps their latest values in refs.

2. Share the instance with sibling panels

GrafloriaProvider wraps the canvas and its sibling inspector. useGrafloria returns the mounted DiagramInstance, or null before mount. Children passed to the flow can use the hook without an outer provider; siblings need the shared provider.

Create the inspector imported above. useSelection supplies selection as render state; useOnSelectionChange runs a callback on changes; useViewport supplies the live camera. The selection count and zoom badge update from the instance's events, not from your buttons.

GrafloriaCommentPanel renders the instance's comment store when comments are enabled. The inspector checks for a store before mounting the panel, so it also works with the controlled example above, which has comments disabled.

tsx
import { useState } from 'react';
import {
  GrafloriaCommentPanel,
  useGrafloria,
  useOnSelectionChange,
  useSelection,
  useViewport,
} from '@grafloria/react';

export function Inspector() {
  const diagram = useGrafloria();
  const selection = useSelection();
  const { zoom, x, y } = useViewport();
  const [lastSelected, setLastSelected] = useState('None');
  useOnSelectionChange(({ nodes }) => setLastSelected(nodes[0]?.id ?? 'None'));
  const comments = diagram?.getCommentStore();

  return (
    <aside style={{ width: 240 }}>
      <button disabled={!diagram} onClick={() => diagram?.fitView()}>Fit</button>
      <p>{selection.nodes.length} selected nodes · {selection.edges.length} selected edges</p>
      <p>First selected node: {lastSelected}</p>
      <p>Zoom: {Math.round(zoom * 100)}%</p>
      <p>Origin: {Math.round(x)}, {Math.round(y)}</p>
      {comments && <GrafloriaCommentPanel store={comments} style={{ height: 260 }} />}
    </aside>
  );
}

Render <ControlledEditor /> from your existing App and run npm run dev. You see two React cards, their connecting edge, the Pipeline zone, canvas plugins and the sibling inspector. Selecting a card changes its border and the inspector's selection state. Compare the custom React nodes demo.

The inspector before a canvas publishes its instance: Fit is disabled, selection is empty, and zoom reads 100%.

The node component remains in your React tree through a portal, so context and local state work inside it. Selection and node-change events refresh the portal; the binding also watches the node's data and metadata changes. Moving the host during a drag does not require a component render for every frame. For data-driven calculations, continue with Compute connected data.

3. Let the instance own a viewer

Use defaultNodes, defaultEdges and defaultGroups to seed an uncontrolled canvas once. Later changes to those defaults do not replace the graph. This viewer renders two built-in nodes and a comment panel, disables editing, and uses the OS color scheme.

tsx
import { GrafloriaFlow, GrafloriaProvider } from '@grafloria/react';
import type { EdgeSpec, GroupSpec, NodeSpec } from '@grafloria/renderer';
import { Inspector } from './Inspector';

const nodes: NodeSpec[] = [
  { id: 'source', position: { x: 60, y: 80 }, label: 'Source' },
  { id: 'target', position: { x: 340, y: 80 }, label: 'Target' },
];
const edges: EdgeSpec[] = [{ source: 'source', target: 'target' }];
const groups: GroupSpec[] = [
  { id: 'review', label: 'Review', children: ['source', 'target'], padding: 32 },
];

export function PipelineViewer() {
  return (
    <GrafloriaProvider>
      <div style={{ display: 'flex', gap: 16 }}>
        <div style={{ height: 400, flex: 1, minWidth: 0 }}>
          <GrafloriaFlow
            defaultNodes={nodes} defaultEdges={edges} defaultGroups={groups}
            readonly colorMode="system" comments commentsViewer="reviewer"
            fitView
          />
        </div>
        <Inspector />
      </div>
    </GrafloriaProvider>
  );
}

Render <PipelineViewer /> instead of the editor to see this separate viewer. comments creates the store; commentsViewer identifies its viewer. Thread authoring and shared stores are covered in presence and comments.

Source and Target appear inside Review beside the inspector and an empty Comments panel.

4. Render custom widget content

GrafloriaDashboard uses the same portal idiom for widgets. A widgetTypes entry selects a React component by widget kind; unregistered kinds use the shipped painters. This board combines the built-in KPI painter with an app-specific release card.

Type the board data with DashboardWidgetSpec. The custom component receives WidgetProps: the widget spec and its data payload.

tsx
import { GrafloriaDashboard } from '@grafloria/react';
import type { WidgetProps } from '@grafloria/react';
import type { DashboardWidgetSpec } from '@grafloria/element';

function ReleaseCard({ widget, data }: WidgetProps) {
  return (
    <article style={{ height: '100%', boxSizing: 'border-box', padding: 16 }}>
      <strong>{widget.title}</strong>
      <p>{String(data['stage'] ?? '')}</p>
      <small>Widget: {widget.id}</small>
    </article>
  );
}

const widgets: DashboardWidgetSpec[] = [
  { id: 'jobs', kind: 'kpi', span: 2, data: { label: 'Jobs', value: '24' } },
  { id: 'release', kind: 'release', span: 4, title: 'Release review', data: { stage: 'Ready for approval' } },
];
const widgetTypes = { release: ReleaseCard };

export function ReleaseBoard() {
  return (
    <GrafloriaDashboard
      widgets={widgets} widgetTypes={widgetTypes}
      options={{ columns: 6 }} style={{ height: 340 }}
    />
  );
}

Render <ReleaseBoard /> from App to see the KPI and release card. The dashboard's runtime state belongs to its handle rather than the flow hooks. For tabs, layout events and persistence, use Build a dashboard; compare the live dashboard builder.

The built-in Jobs KPI displays 24 beside the custom Release review card and its Ready for approval text.

5. Host a complete diagram spec

GrafloriaDiagram hosts object specs or their JSON strings. This example renders Source connected to Target and displays a status when the instance is ready.

tsx
import { useState } from 'react';
import { GrafloriaDiagram } from '@grafloria/react';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';

const nodes: NodeSpec[] = [
  { id: 'source', position: { x: 60, y: 80 }, label: 'Source' },
  { id: 'target', position: { x: 340, y: 80 }, label: 'Target' },
];
const edges: EdgeSpec[] = [{ source: 'source', target: 'target' }];

export function SpecViewer() {
  const [ready, setReady] = useState(false);
  return (
    <section>
      <p role="status">{ready ? 'Diagram ready' : 'Mounting diagram'}</p>
      <GrafloriaDiagram
        spec={{ nodes, edges }}
        options={{ fitView: true }}
        colorMode="dark"
        className="spec-viewer"
        style={{ height: 360 }}
        onReady={() => setReady(true)}
      />
    </section>
  );
}

A changed spec or options value replaces the diagram; an equal value recreated during a render does not. colorMode changes apply to the current instance without replacing it. Use this host for document restoration through the documented loader in Save and restore documents, not as a second read of a payload you already loaded.

6. Adopt server-rendered SVG

For an SSR route, call renderToStaticSVG on the server and pass its result to the flow's ssr prop. Import the server function from @grafloria/renderer, outside the client component boundary. Ship the returned CSS as well as the HTML: the SVG uses the diagram's CSS variables.

The following development SSR route uses the same Vite project. It adds separate entry files without replacing the starter's entry, plugins or configuration. The server emits Source and Target with their edge; the browser hydrates the same flow and adopts its SVG.

Create the shared component. Its payload carries the library's StaticRenderResult together with the specs used for both renders. Rendering it without a server payload creates a client-only preview; the SSR route supplies the server's payload instead.

tsx
import { GrafloriaFlow } from '@grafloria/react';
import type { EdgeSpec, NodeSpec, StaticRenderResult } from '@grafloria/renderer';

export interface PageData {
  nodes: NodeSpec[];
  edges: EdgeSpec[];
  ssr: StaticRenderResult;
}

const previewNodes: NodeSpec[] = [
  { id: 'source', position: { x: 60, y: 80 }, label: 'Source' },
  { id: 'target', position: { x: 340, y: 80 }, label: 'Target' },
];
const previewEdges: EdgeSpec[] = [{ id: 'route', source: 'source', target: 'target' }];

export function SsrFlow({ data }: { data?: PageData }) {
  return (
    <GrafloriaFlow
      defaultNodes={data?.nodes ?? previewNodes} defaultEdges={data?.edges ?? previewEdges}
      ssr={data?.ssr} style={{ height: 400 }}
    />
  );
}

Create the server entry. Use the same data on both sides, and assign a distinct instanceId to each server-rendered diagram on a page.

tsx
import { StrictMode } from 'react';
import { renderToString } from 'react-dom/server';
import { renderToStaticSVG } from '@grafloria/renderer';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
import { SsrFlow } from './SsrFlow';
import type { PageData } from './SsrFlow';

export function renderPage() {
  const nodes: NodeSpec[] = [
    { id: 'source', position: { x: 60, y: 80 }, label: 'Source' },
    { id: 'target', position: { x: 340, y: 80 }, label: 'Target' },
  ];
  const edges: EdgeSpec[] = [{ id: 'route', source: 'source', target: 'target' }];
  const ssr = renderToStaticSVG({
    nodes, edges, width: 800, height: 400, instanceId: 'pipeline-ssr',
  });
  const data: PageData = { nodes, edges, ssr };
  const app = renderToString(<StrictMode><SsrFlow data={data} /></StrictMode>);
  const payload = JSON.stringify(data).replace(/</g, '\\u003c');
  return { app, css: ssr.css, payload };
}

Create the browser entry. It reads the server payload and hydrates the existing root rather than creating a second diagram.

tsx
import { StrictMode } from 'react';
import { hydrateRoot } from 'react-dom/client';
import '../index.css';
import '../App.css';
import { SsrFlow } from './SsrFlow';
import type { PageData } from './SsrFlow';

const root = document.getElementById('root');
const payload = document.getElementById('diagram-data');
if (!root || !payload?.textContent) throw new Error('Missing SSR root or diagram payload');
const data: PageData = JSON.parse(payload.textContent);
hydrateRoot(root, <StrictMode><SsrFlow data={data} /></StrictMode>);

Add the development server at the project root. It uses Vite's existing configuration and HTML template, switching only this route's entry script.

js
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { createServer as createViteServer } from 'vite';

async function start() {
const vite = await createViteServer({ server: { middlewareMode: true }, appType: 'custom' });
const server = createServer((request, response) => {
  vite.middlewares(request, response, () => {
    void render(request, response);
  });
});

async function render(request, response) {
  try {
    const url = request.url ?? '/';
    let template = await readFile(new URL('./index.html', import.meta.url), 'utf8');
    template = template.replace('/src/main.tsx', '/src/ssr/entry-client.tsx');
    template = await vite.transformIndexHtml(url, template);
    const { renderPage } = await vite.ssrLoadModule('/src/ssr/entry-server.tsx');
    const { app, css, payload } = renderPage();
    const html = template
      .replace('</head>', `<style>${css}</style></head>`)
      .replace('<div id="root"></div>', `<div id="root">${app}</div>`)
      .replace('</body>', `<script id="diagram-data" type="application/json">${payload}</script></body>`);
    response.writeHead(200, { 'Content-Type': 'text/html' });
    response.end(html);
  } catch (error) {
    if (error instanceof Error) vite.ssrFixStacktrace(error);
    console.error(error);
    response.writeHead(500);
    response.end('SSR failed');
  }
}

server.listen(3000, () => console.log('Open http://localhost:3000'));
}

void start().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
bash
node server.mjs

Open http://localhost:3000. View the response source to find the two node labels and SVG before JavaScript runs; after hydration, the same view accepts selection and node dragging. ssr is initial markup, not a live replacement prop: subsequent model updates go through the instance or controlled inputs. Custom HTML nodes mount during hydration rather than appearing in the server SVG. Compare the live headless rendering demo.

Options that matter

ColorMode has three values:

ValueEffect
lightPins the built-in light theme.
darkPins the built-in dark theme.
systemFollows the OS color scheme and high-contrast setting.

While colorMode is set, it takes precedence over theme. Removing it keeps the last mode. For custom themes and tokenBridge, use Theme a diagram.

OptionTypeDefaultWhat it does
readonlybooleanfalseDisables editing gestures.
enablePanbooleantrueControls panning at mount.
enableZoombooleantrueControls zooming at mount.
zoomSensitivitynumber0.1Sets the zoom response.
dragThresholdnumber4Sets the movement threshold before a drag starts.
maxZoomnumber3Caps the zoom scale.
highlighterConfigboolean or partial configurationfalseEnables hover, selection, validation and connection-target outlines.
highlightConnectedboolean or optionsfalseEmphasizes the selected nodes' lines and fades others.

onSelectionChange receives selected nodes and edges; use it for a component-level callback rather than a subscription hook when the owning component already has the flow. onConnect receives the created link, and onNodeClick and onEdgeClick receive the clicked model plus world coordinates. React uses these callback names without a $ suffix and uses className, not class.

layout and onLayoutDone belong to declarative layout. rendererConfig and interaction pass configuration into the renderer and input binder; use edge routing and connection gestures for their task-specific fields. collab and onCollabReady configure a mount-time session; use Sync collaborators for its transport and lifecycle.

Was this page helpful?

React: state and content — Grafloria