12

I'm using onDrag method in react js. I want to happen drag while i'm dragging the image, but I don't want to show the ghost image. I used css "-webkit-user-drag:none", but it is completely prevent the drag functionality. I want both to work in same time.

Sample code,

<img
                    style={{ left: `${pixels}px` }}
                    onDrag={this.dragOn.bind('start')}
                    onDragEnd={this.dragOn.bind(this, 'end')}
                    alt=""
                    height="20"
                    width="15"
                    draggable="true"
Umesh
  • 2,704
  • 19
  • 21
Sathya
  • 1,704
  • 3
  • 36
  • 58

3 Answers3

10

First create a small transparent image in componentDidMount:

componentDidMount() {
  this.dragImg = new Image(0,0);
  this.dragImg.src =
  'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
}

Then in your handler for onDragStart:

handleOnDragStart = e => {
  e.dataTransfer.setDragImage(this.dragImg, 0, 0);
}

Note: You have to call the setDragImage method in the onDragStart handler. It won't work in the method used for onDrag.

Paul Freeman
  • 135
  • 2
  • 7
4

In the documentation for the html5 drag-and-drop standard here: https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations#dragfeedback

you can see how to change this translucent image it appears under the cursor. You can set to something more discrete image (or canvas) or even to a blank image like a new Image()

event.dataTransfer.setDragImage(new Image(), 0, 0);

but I would advise against using a blank image since you need some sort of visual cue for the drag-and-drop.

vassiliskrikonis
  • 566
  • 2
  • 10
0

I would also add css property : user-select: none;for the entire drag and drop area, since selecting area as text (enable by default in many cases), cause the text itself to be draggable, which might look the same as dragging your draggable element (image or just a div), when in fact it is not, further causing confusions and bugs.

user8376713
  • 397
  • 3
  • 5