DEV Community

Tao Wen
Tao Wen

Posted on

Make react svg component draggable

Create a Rect component

It does nothing special. Just a dummy wrapper of <rect>

Add d3-drag

We use ReactDOM to find out the dom node. And use d3-drag to respond to mouse enter and mouse move. Although svg does not have drag drop event, d3-drag simulated it by intercepting window wide mouse events.

Setting x y attribute works. However, dragging will cause the rect "jump" to the position of mouse cursor. We would want it to stay there.

Make dragging starts without "jump"

The trick is to set the subject to have x y properties from the target rect. The relative position will be kept

How about circle?

For circle, we need to change x to cx, y to cy. And it seems working. The relative position is still kept.

We noticed the code is nearly the same as Rect. Can we make it generic?

Support both circle and rect

Just like change from rect to circle, we changed from x to cx, y to cy. This time, we use translate(x, y) to set the x y coordinate transformation. This transform attribute is supported by both rect and circle, so we only need to make one makeDraggable.

How about group?

It also works on <g>. However, we have to make the individual rect and circle undraggable, otherwise the dragged element will be rect or circle instead of the group.

Discussion (0)