Interaction Recipes

The 13 Phase-2 interaction callback props (onNodeClick, onNodeHover, onNodeContextMenu, onNodeDragEnd, etc.) are designed so most host code needs zero apiRef plumbing — just wire callbacks and React state. This page collects the common recipes.

Hover tooltip

Show a floating tooltip next to the cursor when hovering a node:

import { useState } from "react";
import { GraphCanvas, type NodePointerEvent } from "@kineviz/gl";

export function GraphWithTooltip() {
  const [tooltip, setTooltip] = useState<{ id: string; x: number; y: number } | null>(null);

  return (
    <div style={{ position: "relative" }}>
      <GraphCanvas
        data={graph}
        forceLayout
        onNodeHover={(e: NodePointerEvent | null) => {
          if (!e) setTooltip(null);
          else setTooltip({ id: e.nodeId, x: e.canvasPos[0], y: e.canvasPos[1] });
        }}
      />
      {tooltip && (
        <div
          style={{
            position: "absolute",
            left: tooltip.x + 12,
            top:  tooltip.y + 12,
            background: "white",
            padding: "4px 8px",
            border: "1px solid #ccc",
            pointerEvents: "none",
          }}
        >
          Node: {tooltip.id}
        </div>
      )}
    </div>
  );
}

onNodeHover(null) fires when the pointer leaves the last hovered node without entering another — perfect for "hide tooltip on leave". The canvasPos is in CSS pixels relative to the canvas's top-left, so it maps directly to the absolutely-positioned tooltip.

Custom right-click menu

Replace the engine's default ContextMenuManager for node right-clicks:

const [menu, setMenu] = useState<{ id: string; x: number; y: number } | null>(null);

<GraphCanvas
  data={graph}
  forceLayout
  onNodeContextMenu={(e) => {
    e.originalEvent.preventDefault();  // suppress engine's default menu
    setMenu({ id: e.nodeId, x: e.canvasPos[0], y: e.canvasPos[1] });
  }}
  onBackgroundClick={() => setMenu(null)}  // click-outside dismiss
/>

{menu && (
  <ul
    role="menu"
    style={{ position: "absolute", left: menu.x, top: menu.y }}
  >
    <li onClick={() => api.selection.selectNodes([menu.id])}>Select</li>
    <li onClick={() => api.nodes.pin([menu.id])}>Pin</li>
    <li onClick={() => api.nodes.remove([menu.id])}>Delete</li>
  </ul>
)}

Calling originalEvent.preventDefault() opts out of the engine's built-in menu for that gesture. Without it, both your menu AND the engine's menu would show.

Multi-select with shift-click

The modifiers field on every pointer event tells you which modifier keys were held:

const [sel, setSel] = useState<SelectionState>({ nodes: [], edges: [] });

<GraphCanvas
  data={graph}
  forceLayout
  selection={sel}
  onSelectionChange={setSel}
  onNodeClick={(e) => {
    if (e.modifiers.shift) {
      // Toggle — add if absent, remove if present
      setSel((prev) => {
        const next = new Set(prev.nodes);
        if (next.has(e.nodeId)) next.delete(e.nodeId);
        else next.add(e.nodeId);
        return { nodes: [...next], edges: prev.edges };
      });
    } else {
      // Replace
      setSel({ nodes: [e.nodeId], edges: [] });
    }
  }}
/>

Combined with the controlled selection prop, you get full multi-select semantics without touching apiRef. The engine just renders whatever selection says.

Drag-to-pin

When the user drags a node, pin it after release so the layout doesn't push it back:

<GraphCanvas
  data={graph}
  forceLayout
  onNodeDragEnd={(e) => {
    // e.draggedNodeIds covers multi-select drag
    api.nodes.pin(e.draggedNodeIds);
  }}
/>

For one-shot reposition without pinning, just don't react to onNodeDragEnd — the engine writes the new position into the graph regardless; pinning just prevents the force simulation from moving it again.

To unpin on double-click:

onNodeDoubleClick={(e) => api.nodes.unpin([e.nodeId])}

Open a detail panel

Open a side panel when a node is clicked, close it on background click:

const [detail, setDetail] = useState<string | null>(null);

<div style={{ display: "flex" }}>
  <GraphCanvas
    data={graph}
    forceLayout
    onNodeClick={(e) => setDetail(e.nodeId)}
    onBackgroundClick={() => setDetail(null)}
  />
  {detail && (
    <aside style={{ width: 300 }}>
      <NodeDetails id={detail} onClose={() => setDetail(null)} />
    </aside>
  )}
</div>

The same pattern works for edges (onEdgeClick, onBackgroundClick).

Dim neighbors on click

Off by default — a plain click just selects, and nothing else in the scene moves. Turn on clickDim (≡ api.emphasis.setClickDimEnabled(true)) and the engine handles the whole interaction itself — no per-click wiring:

<GraphCanvas
  data={graph}
  forceLayout
  clickDim          // click a node/edge to focus it; click again / background to clear
/>
  • Click a node → keep it + its 1-hop neighborhood (nodes and the connecting edges) bright; fade everything else.
  • Click an edge → keep the edge's two endpoint nodes bright (same focus treatment as a node).
  • Click the same target again, or the background → clear.
  • Sizes never change — the dim is opacity only.

Dim is click-driven, not hover-driven — hovering still shows the glow ring (governed independently by api.emphasis.setEmphasisGlowEnabled, on by default), and dragging a node to reposition it does not dim. Under the hood the engine dims with focusContext (direct opacity), so it renders reliably even when the force layout has settled and the render loop is idle. See the runnable Les Misérables — click to dim example.

For programmatic neighborhood focus (e.g. driven by an external list row, not a canvas click), call the effect directly:

const { nodeIds } = api.emphasis.traceNeighbor({ nodeIds: ["valjean"], depth: 1 });
api.emphasis.retargetFocusContext(nodeIds, { contextOpacity: 0.12, contextEdgeOpacity: 0.06 });
// ... later
api.emphasis.stopAll("focusContext");

Background click for canvas-level actions

onBackgroundClick fires when the user clicks empty canvas (no node, no edge under the pointer). Use it for clearing selection, dismissing menus, or noting the click position for a "create new node here" affordance:

<GraphCanvas
  data={graph}
  forceLayout
  onBackgroundClick={(e) => {
    // e.worldPos is the 3D scene position under the cursor — perfect for
    // "create node here" interactions
    api.nodes.add([{ id: `n-${Date.now()}`, position: { x: e.worldPos[0], y: e.worldPos[1], z: 0 } }]);
  }}
/>

Event payload reference

All 13 pointer callbacks receive a payload extending PointerEventBase:

Field Type Notes
originalEvent MouseEvent Native event; call preventDefault() to suppress default behaviour
canvasPos [number, number] CSS pixels, origin top-left of canvas
worldPos [number, number, number] 3D scene coordinates
modifiers { shift, ctrl, meta, alt } Snapshot at event time
nodeId / edgeId string On node/edge targeted callbacks only

Drag callbacks add startWorld, deltaWorld, draggedNodeIds for the full drag context.

See also