#Adding a new node on connecting edges

1 messages · Page 1 of 1 (latest)

lost lantern
#

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>
  )
}

dense tangle
#

You could just use a flag that you set to true in onConnectStart and then reset in onConnectEnd and if the flag is set to true just avoid adding new nodes

lost lantern
#

tried it, doesnt work. the addNode function is called after the onConnectEnd

#

it think when i click the handle to start an edge that's when it registers the click instead of when it's connected. if i stop the edge midway without connecting it even then it adds a new node

#

another new thing i figured out, when i let go of the edge when i'm on the canvas, that's when it happens