Automatic graph layout using dagre with React Flow (@xyflow/react). Use when implementing auto-layout, hierarchical layouts, tree structures, or arranging nodes programmatically. Triggers on dagre, auto-layout, automatic layout, getLayoutedElements, rankdir, hierarchical graph.
View on GitHubskills/dagre-react-flow/SKILL.md
February 1, 2026
Select agents to install to:
npx add-skill https://github.com/existential-birds/beagle/blob/main/skills/dagre-react-flow/SKILL.md -a claude-code --skill dagre-react-flowInstallation paths:
.claude/skills/dagre-react-flow/# Dagre with React Flow
Dagre is a JavaScript library for laying out directed graphs. It computes optimal node positions for hierarchical/tree layouts. React Flow handles rendering; dagre handles positioning.
## Quick Start
```bash
pnpm add @dagrejs/dagre
```
```typescript
import dagre from '@dagrejs/dagre';
import { Node, Edge } from '@xyflow/react';
const getLayoutedElements = (
nodes: Node[],
edges: Edge[],
direction: 'TB' | 'LR' = 'TB'
) => {
const g = new dagre.graphlib.Graph();
g.setGraph({ rankdir: direction });
g.setDefaultEdgeLabel(() => ({}));
nodes.forEach((node) => {
g.setNode(node.id, { width: 172, height: 36 });
});
edges.forEach((edge) => {
g.setEdge(edge.source, edge.target);
});
dagre.layout(g);
const layoutedNodes = nodes.map((node) => {
const pos = g.node(node.id);
return {
...node,
position: { x: pos.x - 86, y: pos.y - 18 }, // Center to top-left
};
});
return { nodes: layoutedNodes, edges };
};
```
## Core Concepts
### Coordinate System Difference
**Critical:** Dagre returns center coordinates; React Flow uses top-left.
```typescript
// Dagre output: center of node
const dagrePos = g.node(nodeId); // { x: 100, y: 50 } = center
// React Flow expects: top-left corner
const rfPosition = {
x: dagrePos.x - nodeWidth / 2,
y: dagrePos.y - nodeHeight / 2,
};
```
### Node Dimensions
Dagre requires explicit dimensions. Three approaches:
**1. Fixed dimensions (simplest):**
```typescript
g.setNode(node.id, { width: 172, height: 36 });
```
**2. Per-node dimensions from data:**
```typescript
g.setNode(node.id, {
width: node.data.width ?? 172,
height: node.data.height ?? 36,
});
```
**3. Measured dimensions (most accurate):**
```typescript
// After React Flow measures nodes
g.setNode(node.id, {
width: node.measured?.width ?? 172,
height: node.measured?.height ?? 36,
});
```
### Layout Directions
| Value | Direction | Use Case |
|-------|-----------|----------|
| `TB`