How to create a custom node in reactflow

How to create a custom node in reactflow


In this post I will walk you through how to create a custom node using reactflow.

Few days back, I decided to build a flow builder using reactflow as part of a frontend coding challenge. It was my first time playing around with reactflow and I struggled a bit to create a custom node using the same.

If you are trying to figure out how to create a custom node using reactflow, this post is for you.

I am assuming you know how to setup a react project and to install reactflow. (feel free to refer this page to understand how to create a new react project using vite).

Follow the below steps to create a custom node

Create a new component, lets give it a name CustomNode

import { Handle, Position } from “reactflow”;
import { BiMessageRoundedDetail } from “react-icons/bi”;
import { BiLogoWhatsapp } from “react-icons/bi”;
import “../assets/styles/CustomNode.css”;

export const CustomNode = ({ data }) => {
return (
<div className=”custom-node”>
<Handle type=”target” position={Position.Left} id=”target” />
<div className=”custom-node__header”>
<div>
<BiMessageRoundedDetail />
<div className=”custom-node__title”>Send message</div>
</div>
<div className=”custom-node__whatsapp-icon”>
<BiLogoWhatsapp />
</div>
</div>
<div className=”custom-node__text”>{data?.label}</div>
<Handle type=”source” position={Position.Right} id=”source” />
</div>
);
};

Style the component according to your requirement.

Keep a constant variable nodeTypes and set the value as follows const nodeTypes = { textUpdater: CustomNode };

here, replace textUpdater with the name of your choice.
CustomNode is the component we have created previously.

Pass the nodeTypes to ReactFlow component along with the other values

<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
onInit={setReactFlowInstance}
onDrop={onDrop}
onDragOver={onDragOver}
onNodeClick={onNodeClick}
nodeTypes={nodeTypes}
fitView
/>

With this changes, you will be able to see your custom node in action..

Feel free to comment or reach out to me if you face issues dealing with custom nodes or reactflow, I will be more than happy to help! Cheers.

Leave a Reply

Your email address will not be published. Required fields are marked *