SkilVaultSign inStart free

Catalogue / react-flow-node-kit

react-flow-node-kit

Older skill: source not recordedSignedBuilds custom React Flow node components with typed data interfaces, top/bottom handles, editable titles, selection-aware resizing, and Zustand store wiring, then registers them in the canvas, add-block menu and connect menu. Use when the user says "add a custom node to React Flow", "build a workflo…
---
name: react-flow-node-kit
description: >-
  Builds custom React Flow node components with typed data interfaces,
  top/bottom handles, editable titles, selection-aware resizing, and Zustand
  store wiring, then registers them in the canvas, add-block menu and connect
  menu. Use when the user says "add a custom node to React Flow", "build a
  workflow editor node", "wire a node to our Zustand store", or "register a
  new node type in the canvas". Not for installing dependencies, running the
  dev server, or persisting workflows to a backend.
---

Custom React Flow node, end to end

Map the project before writing

  1. Check the installed @xyflow/react, React, and Zustand versions; type against what is installed.
  2. Find the real locations of: the node type union (AppNode), the store, the canvas nodeTypes registration, node exports, default-node factory, add-block menu, connect menu.
  3. Pick a PascalCase component name (ReadingCheckpointNode), a matching data interface name, and a stable kebab-case type id (reading-checkpoint). All four integration points must agree on the id.
  4. Editing app files is the task here — but confirm anything beyond it: installing packages, saving workflows to a server, or touching unrelated modules.

The pieces

| Piece | Shape | |---|---| | Data interface | interface XData extends Record<string, unknown> (React Flow requires record compatibility) | | Node alias | type X = Node<XData, 'x-id'> | | Component | memo(function XNode({ id, data, selected, width, height }: NodeProps<X>)) | | Store updates | immutable: spread the node, merge only the changed data fields | | Handles | target on top, source on bottom, stable id per handle |

Complete example: a reading-checkpoint node

One self-contained module with types, store, node component, canvas and both menus:

import { memo, useCallback } from 'react';
import { create } from 'zustand';
import {
  ReactFlow, Background, Handle, Position, NodeResizer,
  applyNodeChanges, applyEdgeChanges, addEdge,
  type Node, type NodeProps, type Edge, type NodeChange,
  type EdgeChange, type Connection,
} from '@xyflow/react';
import '@xyflow/react/dist/style.css';

export interface CheckpointData extends Record<string, unknown> {
  title: string;
  description?: string;
  shelfCode: string;
}
export type ReadingCheckpoint = Node<CheckpointData, 'reading-checkpoint'>;
export type AppNode = ReadingCheckpoint;
export type CanvasMode = 'editing' | 'viewing';

export function patchNode(nodes: AppNode[], id: string,
                          patch: Partial<CheckpointData>): AppNode[] {
  return nodes.map(node => node.id === id
    ? { ...node, data: { ...node.data, ...patch } } : node);
}

export function newCheckpoint(id: string, x: number, y: number): ReadingCheckpoint {
  return { id, type: 'reading-checkpoint', position: { x, y },
    data: { title: 'Reading checkpoint', description: 'Review the next shelf.',
            shelfCode: 'LOCAL' } };
}

interface EditorState {
  nodes: AppNode[];
  edges: Edge[];
  canvasMode: CanvasMode;
  updateNode: (id: string, patch: Partial<CheckpointData>) => void;
  addCheckpoint: (node: ReadingCheckpoint) => void;
  connect: (connection: Connection) => void;
  changeNodes: (changes: NodeChange<AppNode>[]) => void;
  changeEdges: (changes: EdgeChange[]) => void;
  setMode: (mode: CanvasMode) => void;
}

export const useReadingEditor = create<EditorState>()((set) => ({
  nodes: [newCheckpoint('reading-start', 40, 70)],
  edges: [], canvasMode: 'editing',
  updateNode: (id, patch) => set(state => state.canvasMode === 'editing'
    ? { nodes: patchNode(state.nodes, id, patch) } : state),
  addCheckpoint: node => set(state => state.canvasMode === 'editing'
    ? { nodes: [...state.nodes, node] } : state),
  connect: connection => set(state => state.canvasMode === 'editing'
    ? { edges: addEdge(connection, state.edges) } : state),
  changeNodes: changes => set(state => ({ nodes: applyNodeChanges(
    state.canvasMode === 'editing' ? changes
      : changes.filter(change => change.type === 'select'), state.nodes) })),
  changeEdges: changes => set(state => ({ edges: applyEdgeChanges(
    state.canvasMode === 'editing' ? changes
      : changes.filter(change => change.type === 'select'), state.edges) })),
  setMode: canvasMode => set({ canvasMode }),
}));

export const ReadingCheckpointNode = memo(function ReadingCheckpointNode({
  id, data, selected, width, height,
}: NodeProps<ReadingCheckpoint>) {
  const updateNode = useReadingEditor(state => state.updateNode);
  const mode = useReadingEditor(state => state.canvasMode);
  const editing = mode === 'editing';
  const changeTitle = useCallback((title: string) => {
    updateNode(id, { title });
  }, [id, updateNode]);
  return <>
    {editing && <NodeResizer isVisible={Boolean(selected)} minWidth={230}
      minHeight={110} lineStyle={{ borderColor: '#48626b' }}
      handleStyle={{ background: '#48626b' }} />}
    <article aria-label="Reading checkpoint" style={{
      position: 'relative', boxSizing: 'border-box', overflow: 'hidden',
      borderRadius: '0.5rem', border: `2px solid ${selected ? '#48626b' : '#a9b3b6'}`,
      boxShadow: selected ? '0 3px 8px #23383d33' : 'none',
      background: '#f8faf9', color: '#20353b',
      width: width ?? 310, height: height ?? 'auto',
    }}>
      <Handle id="incoming" type="target" position={Position.Top}
        isConnectable={editing} style={{ background: '#48626b' }} />
      <header style={{ padding: '0.8rem', borderBottom: '1px solid #a9b3b6' }}>
        {editing ? <input className="nodrag nowheel" aria-label="Checkpoint title"
          value={data.title} onChange={event => changeTitle(event.target.value)}
          style={{ width: '100%', boxSizing: 'border-box' }} />
          : <h3 style={{ margin: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>{data.title}</h3>}
      </header>
      <section style={{ padding: '0.8rem' }}>
        <p>{data.description ?? 'No review instruction supplied.'}</p>
        <small>Shelf: {data.shelfCode}</small>
      </section>
      <Handle id="outgoing" type="source" position={Position.Bottom}
        isConnectable={editing} style={{ background: '#48626b' }} />
    </article>
  </>;
});

const nodeTypes = { 'reading-checkpoint': ReadingCheckpointNode };

export function AddBlockMenu() {
  const add = useReadingEditor(state => state.addCheckpoint);
  const mode = useReadingEditor(state => state.canvasMode);
  return <button disabled={mode !== 'editing'} onClick={() => {
    add(newCheckpoint(crypto.randomUUID(), 80, 240));
  }}>Add reading checkpoint</button>;
}

export function ConnectMenu() {
  const nodes = useReadingEditor(state => state.nodes);
  const connect = useReadingEditor(state => state.connect);
  const mode = useReadingEditor(state => state.canvasMode);
  const selected = nodes.filter(node => node.selected);
  return <button disabled={mode !== 'editing' || selected.length !== 2}
    onClick={() => {
      if (selected.length !== 2) return;
      connect({ source: selected[0].id, target: selected[1].id,
                sourceHandle: 'outgoing', targetHandle: 'incoming' });
    }}>Connect selected checkpoints in canvas order</button>;
}

export function ReadingCanvas() {
  const nodes = useReadingEditor(state => state.nodes);
  const edges = useReadingEditor(state => state.edges);
  const mode = useReadingEditor(state => state.canvasMode);
  const changeNodes = useReadingEditor(state => state.changeNodes);
  const changeEdges = useReadingEditor(state => state.changeEdges);
  const connect = useReadingEditor(state => state.connect);
  const setMode = useReadingEditor(state => state.setMode);
  return <section>
    <nav aria-label="Workflow actions">
      <button onClick={() => setMode(mode === 'editing' ? 'viewing' : 'editing')}>
        Switch to {mode === 'editing' ? 'viewing' : 'editing'}
      </button><AddBlockMenu /><ConnectMenu />
    </nav>
    <div style={{ height: '32rem', width: '100%' }}>
      <ReactFlow<AppNode> nodes={nodes} edges={edges} nodeTypes={nodeTypes}
        onNodesChange={changeNodes} onEdgesChange={changeEdges} onConnect={connect}
        nodesDraggable={mode === 'editing'} nodesConnectable={mode === 'editing'}
        deleteKeyCode={mode === 'editing' ? 'Backspace' : null} fitView>
        <Background />
      </ReactFlow>
    </div>
  </section>;
}

Why the example is shaped this way

  • `nodeTypes` at module scope. Recreating it per render remounts nodes.
  • One Zustand selector per field. Selecting the whole store rerenders every node on any change.
  • `memo` is not enough. Updates must stay immutable — merge data, never mutate it, and preserve id, type, position.
  • `useCallback` deps include both id and the store action.
  • Edit/view mode guards the store, not just the inputs. Hiding an input while the action stays callable is not permission enforcement.
  • `nodrag` / `nowheel` on inputs stop title typing from dragging the node.

Wire it into an existing app

  1. Add the data interface and node alias to the project's types module; extend the AppNode union; give every required field a default.
  2. Add the component file; export it from the node directory's index if one exists. No leftover {{...}} placeholders or unresolvable aliases.
  3. Add the immutable update and default-creation actions to the existing store — do not fork a competing canvas state.
  4. Register the exact type id in the canvas nodeTypes.
  5. Add the default to the add-block menu and matching handle ids to the connect menu; keep the project's duplicate/cycle/connection rules.
  6. Match the app's theme tokens for borders, selection ring, resizer handles, and shadows. Give inputs accessible labels and a visible focus ring.

Verify

| Check | How | |---|---| | Types compile | Project typecheck with installed dependencies | | Title updates | Change a title; assert only that node's data changed | | Unknown id | patchNode on a missing id returns the same array contents | | Position preserved | Update data; position and extra fields untouched | | Mode gating | Viewing mode blocks editing, resizing, connecting | | Handles | Draw an edge into the top handle and out of the bottom in a browser |

Syntax-only transpilation does not prove interaction; check handles, resizing and read-only behavior in a real browser session.

Never

  • Register a type id that differs from the Node alias, defaults, or menus.
  • Mutate node data in place, or replace the whole data object to change one field.
  • Recreate nodeTypes per render or select the entire store in a node.
  • Leave edit-mode capabilities reachable in viewing mode via store actions.
  • Install packages, save workflows to a server, or modify files beyond the agreed scope without asking.