DEV Community

Tao Wen
Tao Wen

Posted on

14 1

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.

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay