Create node objects

Outside of your React component, create an array of node objects with these required properties:

  • id: A unique identifier for each node
  • position: The x and y coordinates
  • data: An object for storing custom data

We can set the type of the first node to input and the second node to output. These are built-in node types, that come with a different set of handles. This is optional, but it means that the first node will only have a source handle and the second node will only have a target handle.

const initialNodes = [
  {
    id: 'n1',
    position: { x: 0, y: 0 },
    data: { label: 'Node 1' },
    type: 'input',
  },
  {
    id: 'n2',
    position: { x: 100, y: 100 },
    data: { label: 'Node 2' },
    type: 'output',
  },
];
Add nodes to the flow

Now we can pass our initialNodes array to the <ReactFlow /> component using the nodes prop:

<ReactFlow nodes={initialNodes}>
  <Background />
  <Controls />
</ReactFlow>
Flow with nodes

This gives us a flow with two labeled nodes 🎉

Example: learn/building-a-flow-2

App.jsx
import { ReactFlow, Controls, Background } from '@xyflow/react';
import '@xyflow/react/dist/style.css';
 
const initialNodes = [
  {
    id: 'n1',
    data: { label: 'Node 1' },
    position: { x: 0, y: 0 },
    type: 'input',
  },
  {
    id: 'n2',
    data: { label: 'Node 2' },
    position: { x: 100, y: 100 },
    type: 'output',
  },
];
 
function Flow() {
  return (
    <div style={{ height: '100%' }}>
      <ReactFlow nodes={initialNodes} fitView colorMode="system">
        <Background />
        <Controls />
      </ReactFlow>
    </div>
  );
}
 
export default Flow;
index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>React Flow Example</title>
    <style>
      html,
      body {
        margin: 0;
        font-family: sans-serif;
      }
 
      #app {
        width: 100vw;
        height: 100vh;
      }
    </style>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="./index.jsx"></script>
  </body>
</html>
index.jsx
import { createRoot } from 'react-dom/client';
import App from './App';
 
const container = document.querySelector('#app');
const root = createRoot(container);
 
root.render(<App />);

We have several built-in nodes that you can explore in the node reference. However, once you start building your own application, you will want to use custom nodes.

Adding edges

Now that we have two nodes, let’s connect them with an edge.