I have a list of images that i can drap and drop, when dragging starts on image i store it’s URL in a state like this:
JavaScript
x
10
10
1
<img
2
alt="dummy-img"
3
src="https://dummyimage.com/200x100/c916c9/fff.jpg"
4
draggable="true"
5
onDragStart={(e) => {
6
setURL(e.target.src);
7
//console.log(URL);
8
}}
9
/>
10
When dropping it i use that state URL to display the image:
JavaScript
1
10
10
1
<div
2
ref={ref}
3
onDragOver={(e) => e.preventDefault()}
4
onDrop={(e) => {
5
e.preventDefault();
6
console.log(e);
7
handleDrop(e);
8
}}
9
></div>
10
But I was wondering if I could use the event e
produced by onDrop
to get the URL of the image, without creating another HTML img…
I want to do this to see if it’s possible to drop online images directly.
Advertisement
Answer
You can use event.dataTransfer.getData('text/html')
to get the HTML of the dropped image. Then, you can use a DOMParser
to read the source of the image, which works both for images on the page and images dropped from other sites.
Example:
JavaScript
1
9
1
let dropArea = document.getElementById('dropArea');
2
dropArea.addEventListener('dragover', e => e.preventDefault());
3
dropArea.addEventListener('drop', function(e) {
4
e.preventDefault();
5
let html = e.dataTransfer.getData('text/html');
6
let src = new DOMParser().parseFromString(html, "text/html")
7
.querySelector('img').src;
8
console.log(src);
9
});
JavaScript
1
2
1
<img src="https://dummyimage.com/200x100/c916c9/fff.jpg" draggable="true">
2
<div id="dropArea" style="height: 100px; background: dodgerblue;">Drop here</div>