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"
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"
Share
Improve this question
edited Aug 16, 2017 at 7:29
Umesh
2,73220 silver badges24 bronze badges
asked Aug 16, 2017 at 7:21
SathyaSathya
1,7343 gold badges38 silver badges59 bronze badges
3 Answers
Reset to default 10First 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
.
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.
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.