mcpField
R
react-flow-usage

react-flow-usage

github.com/thedogwiththedataonit開発637 回インストール40 週間前に更新
リポジトリ

react-flow-usage について

react-flow-usageは、React Flow(@xyflow/react v12+)でノードベースのUIを構築するためのスキルガイドです。ワークフローエディターやフロー図向けに、コンポーネント、状態、性能、レイアウト、操作方法を扱います。

主な機能

  1. 01カスタムノードとエッジのパターン
  2. 02フロー状態とフック
  3. 03ドラッグ&ドロップ操作
  4. 04フローの保存と復元
  5. 05レイアウトと性能の指針

活用シーン

  1. 01ワークフローエディターの構築
  2. 02カスタムノードUIの作成
  3. 03フローの保存と復元の追加
  4. 04大規模グラフの性能改善

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/thedogwiththedataonit/react-flow --skill react-flow-usage

インストール後、Claude Code で/react-flow-usageを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

.gitignore
AGENTS.md
ALL_LINKS.md
README.md
metadata.json
rules/
interaction-drag-drop.md
_sections.md
hook-use-nodes-data.md
_template.md
edge-connection-validation.md
layout-auto-dagre.md
node-custom-handles.md
setup-nodetypes-outside.md
setup-imports-css.md
perf-memo-custom-components.md
state-save-restore.md
typescript-typed-nodes-edges.md

詳細

React Flow 使用ガイド

React Flow(@xyflow/react v12+)を使用して、本番環境に対応したノードベースの UI を構築するための包括的なパターンとベストプラクティスです。

このスキルを使用する場面

次の場合に、これらのガイドラインを適用してください。

  • ワークフローエディター、フロー図、またはノードベースのインターフェースを構築する
  • カスタムノードまたはエッジコンポーネントを作成する
  • ビジュアルプログラミング向けのドラッグ&ドロップ機能を実装する
  • 100 個以上のノードを含むグラフのパフォーマンスを最適化する
  • フローの状態、保存と復元、または元に戻す/やり直しを管理する
  • dagre、elkjs、またはカスタムアルゴリズムを使用して自動レイアウトを実装する
  • React Flow を TypeScript と統合する

優先度別のルールカテゴリ

優先度カテゴリ重点項目プレフィックス
1セットアップと設定重大setup-
2パフォーマンス最適化重大perf-
3ノードのパターン高node-
4エッジのパターン高edge-
5状態管理高state-
6フックの使用中hook-
7レイアウトと配置中layout-
8インタラクションのパターン中interaction-
9TypeScript との統合中typescript-

クイックスタートのパターン

import { useCallback } from 'react';
import {
  ReactFlow,
  Background,
  Controls,
  MiniMap,
  useNodesState,
  useEdgesState,
  addEdge
} from '@xyflow/react';
import '@xyflow/react/dist/style.css';

const initialNodes = [
  { id: '1', position: { x: 0, y: 0 }, data: { label: 'Node 1' } },
];

const initialEdges = [
  { id: 'e1-2', source: '1', target: '2' },
];

// Define outside component or use useMemo
const nodeTypes = { custom: CustomNode };
const edgeTypes = { custom: CustomEdge };

function Flow() {
  const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
  const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);

  const onConnect = useCallback(
    (params) => setEdges((eds) => addEdge(params, eds)),
    [setEdges]
  );

  return (
    <div style={{ width: '100%', height: '100vh' }}>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        nodeTypes={nodeTypes}
        edgeTypes={edgeTypes}
        fitView
      >
        <Background />
        <Controls />
        <MiniMap />
      </ReactFlow>
    </div>
  );
}

コアコンセプトの概要

ノードの構造
  • id:一意の識別子(必須)
  • position:{ x: number, y: number }(必須)
  • data:カスタムデータオブジェクト(必須)
  • type:組み込みまたはカスタムのタイプ
  • style、className:スタイル設定
  • draggable、selectable、connectable:インタラクションの制御
  • parentId:ネストまたはグループ化されたノード用
  • extent:移動範囲
エッジの構造
  • id:一意の識別子(必須)
  • source:ソースノードの ID(必須)
  • target:ターゲットノードの ID(必須)
  • sourceHandle、targetHandle:特定のハンドル ID
  • type:'default' | 'straight' | 'step' | 'smoothstep' | カスタム
  • animated:アニメーションの有無を示すブール値
  • label:文字列または React コンポーネント
  • markerStart、markerEnd:矢印マーカー
ハンドルの使用方法
  • 位置:Position.Top | Bottom | Left | Right
  • タイプ:'source' | 'target'
  • 1 つのノードで複数のハンドルを使用できます
  • 複数のハンドルには、一意の id プロパティを使用してください

基本的なパターン

カスタムノード
import { memo } from 'react';
import { Handle, Position, NodeProps } from '@xyflow/react';

const CustomNode = memo(({ data, selected }: NodeProps) => {
  return (
    <div className={`custom-node ${selected ? 'selected' : ''}`}>
      <Handle type="target" position={Position.Top} />
      <div>{data.label}</div>
      <Handle type="source" position={Position.Bottom} />
    </div>
  );
});

// IMPORTANT: Define outside component
const nodeTypes = { custom: CustomNode };
カスタムエッジ
import { BaseEdge, EdgeLabelRenderer, getBezierPath, EdgeProps } from '@xyflow/react';

function CustomEdge({ id, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition }: EdgeProps) {
  const [edgePath, labelX, labelY] = getBezierPath({
    sourceX, sourceY, sourcePosition, targetX, targetY, targetPosition,
  });

  return (
    <>
      <BaseEdge path={edgePath} />
      <EdgeLabelRenderer>
        <div style={{
          position: 'absolute',
          transform: `translate(-50%, -50%) translate(${labelX}px,${labelY}px)`,
        }}>
          Custom Label
        </div>
      </EdgeLabelRenderer>
    </>
  );
}
パフォーマンス最適化
// 1. Memoize node/edge types (define outside component)
const nodeTypes = useMemo(() => ({ custom: CustomNode }), []);

// 2. Memoize callbacks
const onConnect = useCallback((params) =>
  setEdges((eds) => addEdge(params, eds)), [setEdges]
);

// 3. Use simple edge types for large graphs
const edgeType = nodes.length > 100 ? 'straight' : 'smoothstep';

// 4. Avoid unnecessary re-renders in custom components
const CustomNode = memo(({ data }) => <div>{data.label}</div>);

主要なフック

  • useReactFlow() - フローインスタンスのメソッドにアクセスします(getNodes、setNodes、fitView など)
  • useNodesState() / useEdgesState() - 変更ハンドラーを備えた管理対象の状態
  • useNodes() / useEdges() - 現在のノード/エッジにリアクティブにアクセスします
  • useNodesData(id) - 特定のノードデータを取得します(useNodes より高いパフォーマンス)
  • useHandleConnections() - ハンドルの接続を取得します
  • useConnection() - 進行中の接続を追跡します
  • useStore() - ストアに直接アクセスします(使用は必要最小限にしてください)

よく使用するパターン

ドラッグ&ドロップ
const onDrop = useCallback((event) => {
  event.preventDefault();
  const type = event.dataTransfer.getData('application/reactflow');
  const position = screenToFlowPosition({
    x: event.clientX,
    y: event.clientY,
  });

  setNodes((nds) => nds.concat({
    id: getId(),
    type,
    position,
    data: { label: `${type} node` },
  }));
}, [screenToFlowPosition]);
保存と復元
const { toObject } = useReactFlow();

// Save
const flow = toObject();
localStorage.setItem('flow', JSON.stringify(flow));

// Restore
const flow = JSON.parse(localStorage.getItem('flow'));
setNodes(flow.nodes || []);
setEdges(flow.edges || []);
setViewport(flow.viewport);
接続の検証
const isValidConnection = useCallback((connection) => {
  // Prevent self-connections
  if (connection.source === connection.target) return false;

  // Custom validation logic
  return true;
}, []);

詳細なルール

包括的なパターンとベストプラクティスについては、カテゴリ別に整理された rules/ ディレクトリ内の各ルールファイルを参照してください。

rules/setup-*.md          - Critical setup patterns
rules/perf-*.md           - Performance optimization
rules/node-*.md           - Node customization patterns
rules/edge-*.md           - Edge handling patterns
rules/state-*.md          - State management
rules/hook-*.md           - Hooks usage
rules/layout-*.md         - Layout and positioning
rules/interaction-*.md    - User interactions
rules/typescript-*.md     - TypeScript integration

コンパイル済みドキュメント全文

すべてのルールと例を展開した完全なガイドについては、AGENTS.md を参照してください。

スクレイピングしたドキュメントの参照先

reactflow.dev からスクレイピングした包括的なドキュメントは scraped/ にあります。

  • 学習:scraped/learn-concepts/、scraped/learn-customization/、scraped/learn-advanced/
  • API:scraped/api-hooks/、scraped/api-types/、scraped/api-utils/、scraped/api-components/
  • 例:scraped/examples-nodes/、scraped/examples-edges/、scraped/examples-interaction/、scraped/examples-layout/
  • UI コンポーネント:scraped/ui-components/
  • チュートリアル:scraped/learn-tutorials/
  • トラブルシューティング:scraped/learn-troubleshooting/

よくある問題

  1. エッジを作成できない - onConnect ハンドラーを追加してください
  2. ノードをドラッグできない - nodesDraggable プロパティを確認してください
  3. CSS が読み込まれない - @xyflow/react/dist/style.css をインポートしてください
  4. useReactFlow がプロバイダーの外で使われている - <ReactFlowProvider> でラップしてください
  5. パフォーマンスの問題 - パフォーマンスカテゴリのルールを参照してください
  6. TypeScript のエラー - 適切なジェネリック型 useReactFlow<NodeType, EdgeType>() を使用してください

参考資料

コメント