DEV Community

Tao Wen
Tao Wen

Posted on

Connect react svg components

Connect two rectangles via straight line

The from and to position is hard coded. Can we make the shapes collaboratively figure out these parameters?

Add from and to property

This time, Rect saved its center to its datum. The Line can figure out x1, y1, x2, y2 by querying its from and to node datum.

Make it draggable

Copied the code from https://dev.to/taowen/make-react-svg-component-draggable-2kc . We can see, the line is not following the rectangles. Let's fix it.

Make the connector follow dragging

We added a custom event called moved. When Rect being dragged, the moved event will be handled by both Rect itself and the connected lines. D3 require multiple listener to be registered in its own namespace, so the event name has different suffix.

Add circle

Circle is easier than Rect, as cx and cy is its center. However, due to we have two lines now, the event namespace need to be unique, so assignId is introduced.

Draw line before drawing the rectangles

We can see the line disappeared, because the connected rect is not drawn yet. We need to fix this.

Order should not matter

Introduced another custom event 'nodeAdded'. If the line can not find the node, it will monitor the nodeAdded event to find out if the collaborators all ready.

Top comments (1)

Collapse
 
madlesss profile image
MadlesSs • Edited

Great article! Helped me very much! Just in case someone is gonna fight with updating components position in redux store, just before dispatching the action remove the transform from me me.attr('transform', null) so the component didn't jump the moved distance after render called again and set transformX and transformY to 0 again so it doesn't move when you begin to drag again :)