@xyflow/react.
3 steps ยท 2 connections
Ingest
Transform
Publish
Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.
Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.
Connections must point forward without a cycle.
Try it
Try Publish โ Ingest: it would close a cycle. Then try Ingest โ Publish to add a valid shortcut. The form and canvas use the same validation function.Code
flow-example.tsx
import { useCallback, useId, useState } from "react";
import {
addEdge,
Background,
Controls,
ReactFlow,
useEdgesState,
useNodesState,
} from "@xyflow/react";
import type { Connection, Edge, Node } from "@xyflow/react";
import { connectionError, makeNode, workflowEdges, workflowNodes } from "./flow-data.ts";
import { DemoIcon } from "./demo-icons.tsx";
import "@xyflow/react/dist/style.css";
import "./flow-example.css";
const validationNodes: Node[] = [
makeNode("ingest", "Ingest", 30, 80),
makeNode("transform", "Transform", 260, 180),
makeNode("publish", "Publish", 490, 80),
];
const validationEdges: Edge[] = [
{ id: "ingest-transform", source: "ingest", target: "transform" },
{ id: "transform-publish", source: "transform", target: "publish" },
];
export function FlowExample({ validation = false }: { validation?: boolean }) {
const [nodes, setNodes, onNodesChange] = useNodesState(
validation ? validationNodes : workflowNodes(),
);
const [edges, setEdges, onEdgesChange] = useEdgesState(
validation ? validationEdges : workflowEdges(),
);
const [source, setSource] = useState("publish");
const [target, setTarget] = useState("ingest");
const [message, setMessage] = useState("Connections must point forward without a cycle.");
const selectedSource = nodes.some((node) => node.id === source) ? source : (nodes[0]?.id ?? "");
const selectedTarget = nodes.some((node) => node.id === target)
? target
: (nodes[nodes.length - 1]?.id ?? "");
const sourceId = useId();
const targetId = useId();
const validConnection = useCallback(
(connection: Edge | Connection) =>
nodes.some((node) => node.id === connection.source) &&
nodes.some((node) => node.id === connection.target) &&
!connectionError(connection, edges),
[edges, nodes],
);
const onConnect = useCallback(
(connection: Connection) => {
if (
!nodes.some((node) => node.id === connection.source) ||
!nodes.some((node) => node.id === connection.target)
) {
setMessage("Choose two existing steps.");
return;
}
if (validation) {
const error = connectionError(connection, edges);
if (error) {
setMessage(error);
return;
}
}
setEdges((current) => addEdge(connection, current));
setMessage(`Connected ${connection.source} to ${connection.target}.`);
},
[edges, nodes, setEdges, validation],
);
function reset() {
setNodes(validation ? validationNodes : workflowNodes());
setEdges(validation ? validationEdges : workflowEdges());
setMessage("Connections must point forward without a cycle.");
}
return (
<section
className="flow-example not-prose"
aria-label={validation ? "Connection validation example" : "Workflow example"}
>
<div className="flow-toolbar">
<span>
{nodes.length} steps ยท {edges.length} connections
</span>
<button type="button" className="demo-button demo-button-small" onClick={reset}>
<DemoIcon name="reset" />
Reset diagram
</button>
</div>
<div className="flow-canvas">
<ReactFlow
id={validation ? "validation-flow" : "workflow-flow"}
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
isValidConnection={validation ? validConnection : undefined}
width={740}
height={430}
fitView
fitViewOptions={{ padding: 0.2 }}
minZoom={0.35}
maxZoom={1.8}
colorMode="system"
defaultEdgeOptions={{ type: "smoothstep" }}
>
<Background gap={22} size={1} color="var(--demo-border)" />
<Controls showInteractive={false} />
</ReactFlow>
</div>
{validation && (
<form
className="flow-validation"
onSubmit={(event) => {
event.preventDefault();
onConnect({
source: selectedSource,
target: selectedTarget,
sourceHandle: null,
targetHandle: null,
});
}}
>
<div className="flow-connection-field">
<label htmlFor={sourceId}>From</label>
<span className="demo-select-wrap">
<select
className="demo-select"
id={sourceId}
value={selectedSource}
onChange={(event) => setSource(event.currentTarget.value)}
>
{nodes.map((node) => (
<option key={node.id} value={node.id}>
{String(node.data.label)}
</option>
))}
</select>
<DemoIcon name="chevron-down" />
</span>
</div>
<div className="flow-connection-field">
<label htmlFor={targetId}>To</label>
<span className="demo-select-wrap">
<select
className="demo-select"
id={targetId}
value={selectedTarget}
onChange={(event) => setTarget(event.currentTarget.value)}
>
{nodes.map((node) => (
<option key={node.id} value={node.id}>
{String(node.data.label)}
</option>
))}
</select>
<DemoIcon name="chevron-down" />
</span>
</div>
<button type="submit" className="demo-button" disabled={nodes.length < 2}>
Add connection
</button>
<p role="status">{message}</p>
</form>
)}
{!validation && (
<p className="flow-caption">
Drag a step, connect the handles, or select a connection and press Backspace to remove it.
</p>
)}
</section>
);
}
flow-data.ts
import { Position } from "@xyflow/react";
import type { Connection, Edge, Node } from "@xyflow/react";
export function workflowNodes(): Node[] {
return [
makeNode("request", "New request", 30, 80),
makeNode("validate", "Validate", 260, 80),
makeNode("review", "Review", 490, 30),
makeNode("publish", "Publish", 490, 180),
makeNode("notify", "Notify", 260, 300),
];
}
export function makeNode(id: string, label: string, x: number, y: number): Node {
return {
id,
data: { label },
position: { x, y },
width: 160,
height: 58,
sourcePosition: Position.Right,
targetPosition: Position.Left,
handles: [
{ type: "target", position: Position.Left, x: 0, y: 29 },
{ type: "source", position: Position.Right, x: 160, y: 29 },
],
};
}
export function workflowEdges(): Edge[] {
return [
{ id: "request-validate", source: "request", target: "validate" },
{ id: "validate-review", source: "validate", target: "review", label: "needs review" },
{ id: "validate-publish", source: "validate", target: "publish", label: "approved" },
{ id: "publish-notify", source: "publish", target: "notify" },
];
}
export function connectionError(
connection: Pick<Connection, "source" | "target">,
edges: Edge[],
): string | null {
if (connection.source === connection.target) return "A step cannot connect to itself.";
if (edges.some((edge) => edge.source === connection.source && edge.target === connection.target))
return "Those steps are already connected.";
const pending = [connection.target];
const visited = new Set<string>();
while (pending.length) {
const current = pending.pop();
if (!current || visited.has(current)) continue;
if (current === connection.source) return "That connection would create a cycle.";
visited.add(current);
for (const edge of edges) if (edge.source === current) pending.push(edge.target);
}
return null;
}