0

I am able to add a dynamic node but I am unable to connect the edge by default. If I add a new node I need to provide source and target, how do I provide source and target of a dynamic node?

const initialNodes = [
    {
      id: 'a',
      data: { label: 'Start' },
      position: { x: 250, y: 25 },
      style: { borderRadius: '50%', padding: '10px', color: 'white', backgroundColor: '#6ede87' }
    },
    {
      id: 'z',
      data: { label: 'End' },
      position: { x: 250, y: 700 },
      style: { borderRadius: '50%', padding: '14px', color: 'white', backgroundColor: 'red' }
    },


  ];
const initialEdges = [
    { id: 'e1-2', source: edgeID, target: ++edgeID },

  ]
 const [nodes, setNodes] = useState(initialNodes);
  const [edges, setEdges] = useState(initialEdges);

//adding a new node :
    const newNode = {
      
       type:'selectorNode2',
       id,
      position: {
        x: Math.random() * 500,
        y: Math.random() * 500,
       },
       data: {
         label: `${nameofNode}`,
      },
      style: {
         background: typeofNode === 1 ? '#ff6700' : typeofNode === 2 ? '#ff0072' : typeofNode === 3 ? '#668de3' : '#fffff',
         color: '#ffff',
         border: '1px solid #222138',
         width: 180,
         borderRadius: typeofNode === 2 ? '50px' : '0px',
        

       },
      };

enter image description here

  • You can assign an ID to the node and keep a track of it. Once the tree renders with the new node, you can then watch for the change of your nodes state, and can inject edges into the edges state, keeping your target ID as that of the newly created node. – Harsha Venkataramu Aug 10 '22 at 10:42

0 Answers0