Disable the drag and drop image in React
In this tutorial, we are going to learn about how to disable the drag and drop image in React with the help of the examples.
Consider, that we have the image in our React app:
import React from "react";
function App {
return (
<div>
<img src="https://via.placeholder.com/150" />
</div>
);
}
export default App;
To disable the drag and drop image in React, add the onDragStart
event to the image element and call the event.preventDefault()
method inside it.
The event.preventDefault()
method prevents the browser from default actions, so it disables the image from drag and drop.
Here is an example:
import React from "react";
function App {
return (
<div>
<img src="https://via.placeholder.com/150"
onDragStart={(event)=> event.preventDefault()}
/>
</div>
);
}
export default App;
Similarly, we can disable the drag and drop image by setting an HTML draggable attribute to false
.
Here is an example:
import React from "react";
function App {
return (
<div>
<img src="https://via.placeholder.com/150"
draggable="false"
/>
</div>
);
}
export default App;
The draggable
attribute can accept the following values:
-
true: the element can be dragged.
-
false: the element cannot be dragged.
Disable Drag and Drop image using CSS
We can also disable the drag and drop image by setting the css pointer-events
property to none
.
When we set a pointer-events property to a value "none"
, the element doesn’t respond to any cursor or touch events.
import React from "react";
function App {
return (
<div>
<img src="https://via.placeholder.com/150" />
</div>
);
}
export default App;
img{
pointer-events: none;
}