I have implemented a feature where a new node gets added where you click on the canvas. However, when I attach an edge to a handle it calls the "click" event and that adds a new node. Any way to fix this?
export default function App() {
const [nodes, setNodes, onNodesChange] = useNodesState<CustomNodeType>(initialNodes)
const [edges, setEdges, onEdgesChange] = useEdgesState<CustomEdgeType>(initialEdges)
const reactFlowWrapper = useRef<any>(null)
const [reactFlowInstance, setReactFlowInstance] = useState<any>(null)
const onConnect: OnConnect = useCallback(
(connection) => {
setEdges((edges) => addEdge(connection, edges))
},
[setEdges],
)
const addNode = useCallback(
(event: React.MouseEvent) => {
event.preventDefault()
if (reactFlowWrapper) {
const reactFlowBounds = reactFlowWrapper.current.getBoundingClientRect()
const position = reactFlowInstance.screenToFlowPosition({
x: event.clientX - reactFlowBounds.left,
y: event.clientY - reactFlowBounds.top,
})
const newNode: CustomNodeType = {
id: `node-${nodes.length + 1}`,
type: 'default',
position,
data: { label: `Node ${nodes.length + 1}` },
}
setNodes((nodes) => [...nodes, newNode])
console.log(nodes)
}
},
[nodes, setNodes, reactFlowInstance, reactFlowWrapper],
)
return (
<div ref={reactFlowWrapper} style={{ width: '100vw', height: '100vh' }} onClick={addNode}>
<ReactFlow<CustomNodeType, CustomEdgeType>
nodes={nodes}
nodeTypes={nodeTypes}
onNodesChange={onNodesChange}
edges={edges}
edgeTypes={edgeTypes}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
onInit={setReactFlowInstance}
fitView
>
<Background />
<Controls />
</ReactFlow>
</div>
)
}