9

We got how to prevent drag drop image with jquery with $('img').on('dragstart', function(event) { event.preventDefault(); }); but I want to achieve the same in a react app, and without jquery. How can I do this ? a) locally (image per image) b) globally (for all images of the react app)

I still want to keep control over other interactions, so img { pointer-events: none; } is not a solution.

The goal is to prevent saving image through drag and drop.

Soleil
  • 6,404
  • 5
  • 41
  • 61
  • @ArmanCharan Yes, it (`draggable="false"`) works for images for which `onClick={}` is doing something, but for the others, it works when I do this directly, **but when I click once, the image is kind of selected and then I can drag it for unknown reason**. – Soleil Apr 18 '18 at 11:47
  • As @ArmanCharan mentioned, adding a draggable attribute works as you can see for yourself here: https://codesandbox.io/s/4r6p4jyko4 But it'll be really helpful if you could show us what you have tried till now. Apologies if I misunderstood the question. – Shishir Anshuman Apr 18 '18 at 11:49
  • @ShishirAnshuman As I commented, I see the same specific problem with your quoted example. – Soleil Apr 18 '18 at 12:01

2 Answers2

16

You can use onDragStart:

onDragStart={this.preventDragHandler}

And the handler:

preventDragHandler = (e) => {
  e.preventDefault();
}
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
7

For apps using HTML5, setting draggable={false} in react should accomplish this as well. It will wind up setting the HTML5 draggable attribute to "false".

Another option would be to just use CSS and set pointer-events: none; on the image.

ihake
  • 1,741
  • 1
  • 17
  • 29