Usage with TypeScript
React Flow is written in TypeScript because we value the additional safety barrier it provides. We export all the types you need for correctly typing data structures and functions you pass to the React Flow component. We also provide a way to extend the types of nodes and edges.
Basic usage
Let’s start with the types you need for a simple flow. TypeScript might already infer some of these types, but we will define them explicitly nonetheless.
import { useState, useCallback } from 'react';
import {
ReactFlow,
addEdge,
type Node,
type Edge,
type FitViewOptions,
type OnConnect,
type OnNodesChange,
type OnEdgesChange,
type OnNodeDrag,
type DefaultEdgeOptions,
} from '@xyflow/react';
const initialNodes: Node[] = [
{ id: '1', data: { label: 'Node 1' }, position: { x: 5, y: 5 } },
{ id: '2', data: { label: 'Node 2' }, position: { x: 5, y: 100 } },
];
const initialEdges: Edge[] = [{ id: 'e1-2', source: '1', target: '2' }];
const fitViewOptions: FitViewOptions = {
padding: '5%',
};
const defaultEdgeOptions: DefaultEdgeOptions = {
animated: true,
};
const onNodeDrag: OnNodeDrag = (_, node) => {
console.log('drag event', node.data);
};
function Flow() {
const [nodes, setNodes] = useState<Node[]>(initialNodes);
const [edges, setEdges] = useState<Edge[]>(initialEdges);
const onNodesChange: OnNodesChange = useCallback(
(changes) => setNodes((nds) => changes.applyTo(nds)),
[setNodes],
);
const onEdgesChange: OnEdgesChange = useCallback(
(changes) => setEdges((eds) => changes.applyTo(eds)),
[setEdges],
);
const onConnect: OnConnect = useCallback(
(connection) => setEdges((eds) => addEdge(connection, eds)),
[setEdges],
);
return (
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
onNodeDrag={onNodeDrag}
fitView
fitViewOptions={fitViewOptions}
defaultEdgeOptions={defaultEdgeOptions}
/>
);
}Custom nodes
Working with custom nodes in TypeScript takes two steps: you define a type for each kind of node, and then you use these types in your node components.
Defining a node type
To describe a node, use the Node type with two generic parameters: the shape of its data and its type name. The type name is the same string you use as type on the node and as the key in your nodeTypes object.
import type { Node } from '@xyflow/react';
export type NumberNodeData = { value: number; anotherValue: number };
export type NumberNode = Node<NumberNodeData, 'number'>;
export type TextNodeData = { text: string };
export type TextNode = Node<TextNodeData, 'text'>;
// a union of all the nodes in your app
export type AppNode = NumberNode | TextNode;A node of this type is checked for both its type and its data:
const node: NumberNode = {
id: '1',
type: 'number',
position: { x: 0, y: 0 },
data: { value: 42, anotherValue: 7 },
};Define your node data with type, not with interface. Node data has to be assignable to Record<string, unknown>, and
interfaces don’t have the implicit index signature that this requires.
Typing a node component
To type a custom node component, pass its node type to NodeProps. The props, like data, are then typed accordingly:
import type { NodeProps } from '@xyflow/react';
import type { NumberNode } from './types';
export default function NumberNodeComponent({ data }: NodeProps<NumberNode>) {
return (
<div>
A special number: {data.value} and {data.anotherValue}
</div>
);
}One component for multiple node types
If one component renders several node types, type its props as a union of NodeProps, one for each node type. Checking type then narrows down data:
import type { NodeProps } from '@xyflow/react';
import type { NumberNode, TextNode } from './types';
export default function CustomNodeComponent({ data, type }: NodeProps<NumberNode> | NodeProps<TextNode>) {
if (type === 'number') {
return <div>A special number: {data.value}</div>;
}
return <div>A special text: {data.text}</div>;
}Registering node components
Finally, you register your components in the nodeTypes object. Its keys are the type names from your node types. With satisfies NodeTypes, TypeScript checks that every component is a valid node component while keeping the exact type of your object:
import type { NodeTypes } from '@xyflow/react';
import NumberNodeComponent from './NumberNodeComponent';
import CustomNodeComponent from './CustomNodeComponent';
export const nodeTypes = {
number: NumberNodeComponent,
text: CustomNodeComponent,
} satisfies NodeTypes;Custom edges
Custom edges work the same way. Add your edge types to types.ts with Edge<Data, 'name'>:
import type { Node, Edge } from '@xyflow/react';
// ... your node types
export type CustomEdge = Edge<{ value: number }, 'custom'>;
// a union of all the edges in your app
export type AppEdge = CustomEdge;Then pass the edge type to EdgeProps:
import { getStraightPath, BaseEdge, type EdgeProps } from '@xyflow/react';
import type { CustomEdge } from './types';
export default function CustomEdgeComponent({ id, sourceX, sourceY, targetX, targetY }: EdgeProps<CustomEdge>) {
const [edgePath] = getStraightPath({ sourceX, sourceY, targetX, targetY });
return <BaseEdge id={id} path={edgePath} />;
}Just like your node components, you register edge components in an edgeTypes object:
import type { EdgeTypes } from '@xyflow/react';
import CustomEdgeComponent from './CustomEdgeComponent';
export const edgeTypes = {
custom: CustomEdgeComponent,
} satisfies EdgeTypes;Advanced usage
In a larger app, you work with many different node and edge types, and most React Flow APIs hand you nodes and edges without knowing which kind they are. That’s what the AppNode and AppEdge unions from your types.ts are for: you pass them to React Flow’s components, callbacks and hooks, and then narrow down a node or edge by checking its type.
Built-in nodes and edges
If you also use built-in nodes (input, output, default, group) or edges (straight, step, smoothstep, bezier), extend your unions in types.ts with the BuiltInNode and BuiltInEdge types:
import type { Node, Edge, BuiltInNode, BuiltInEdge } from '@xyflow/react';
// ... your node and edge types
export type AppNode = BuiltInNode | NumberNode | TextNode;
export type AppEdge = BuiltInEdge | CustomEdge;Built-in nodes accept any string as their type. With BuiltInNode in your union, a check like node.type === 'number' no
longer narrows down data. Use a type guard in this case.
State and the <ReactFlow /> component
Type your state with your unions. <ReactFlow /> infers its types from the nodes and edges you pass, so inline callbacks are typed automatically. If you define a callback separately, type it with your union:
import { useCallback } from 'react';
import { ReactFlow, addEdge, useNodesState, useEdgesState, type OnConnect, type OnNodeDrag } from '@xyflow/react';
import { nodeTypes } from './nodeTypes';
import { edgeTypes } from './edgeTypes';
import type { AppNode, AppEdge } from './types';
const initialNodes: AppNode[] = [
{ id: '1', type: 'number', position: { x: 0, y: 0 }, data: { value: 42, anotherValue: 7 } },
{ id: '2', type: 'text', position: { x: 0, y: 100 }, data: { text: 'Hello' } },
];
const initialEdges: AppEdge[] = [];
const onNodeDrag: OnNodeDrag<AppNode> = (_, node) => {
if (node.type === 'number') {
// TypeScript knows that node is a NumberNode here
console.log('drag event', node.data.value);
}
};
export default function Flow() {
const [nodes, , onNodesChange] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
const onConnect: OnConnect = useCallback((connection) => setEdges((eds) => addEdge(connection, eds)), [setEdges]);
return (
<ReactFlow
nodes={nodes}
edges={edges}
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
onNodeDrag={onNodeDrag}
/>
);
}If you manage your nodes and edges yourself, for example with useState or a state management library, type your change handlers with your unions as well:
const onNodesChange: OnNodesChange<AppNode> = (changes) => setNodes((nds) => changes.applyTo(nds));
const onEdgesChange: OnEdgesChange<AppEdge> = (changes) => setEdges((eds) => changes.applyTo(eds));Hooks
Hooks don’t know which nodes and edges your flow contains, so you pass your unions as generics:
import { useReactFlow } from '@xyflow/react';
import type { AppNode, AppEdge } from './types';
export default function Toolbar() {
const { getNodes, updateNodeData } = useReactFlow<AppNode, AppEdge>();
const incrementAll = () => {
getNodes().forEach((node) => {
if (node.type === 'number') {
updateNodeData(node.id, { value: node.data.value + 1 });
}
});
};
return <button onClick={incrementAll}>Increment</button>;
}The same works for hooks you use inside custom nodes, like useNodesData:
import { useNodeConnections, useNodesData, type NodeProps } from '@xyflow/react';
import type { AppNode, TextNode } from './types';
export default function SumNodeComponent({ data }: NodeProps<TextNode>) {
const connections = useNodeConnections({ handleType: 'target' });
const nodesData = useNodesData<AppNode>(connections.map((connection) => connection.source));
const sum = nodesData.reduce((total, { type, data }) => (type === 'number' ? total + data.value : total), 0);
return (
<div>
{data.text}: {sum}
</div>
);
}These generics are not checked against your actual nodes. TypeScript trusts that the flow only contains the nodes and edges you declare, so keep your unions up to date when you add new node or edge types.
Type guards
A type guard is a function that tells TypeScript which type a node has. It’s useful for filtering lists of nodes, and it also works when BuiltInNode is part of your union:
import type { AppNode, NumberNode } from './types';
function isNumberNode(node: AppNode): node is NumberNode {
return node.type === 'number';
}
// nodes is of type AppNode[], e.g. from getNodes()
// numberNodes is of type NumberNode[]
const numberNodes = nodes.filter(isNumberNode);