Search code examples
javascriptreactjsdrag-and-drop

Get src of dropped image from event target


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:

 <img
    alt="dummy-img"
    src="https://dummyimage.com/200x100/c916c9/fff.jpg"
    draggable="true"
    onDragStart={(e) => {
        setURL(e.target.src);
        //console.log(URL);
    }}
/>

When dropping it i use that state URL to display the image:

<div
   ref={ref}
   onDragOver={(e) => e.preventDefault()}
   onDrop={(e) => {
     e.preventDefault();
     console.log(e);
     handleDrop(e);
   }}          
 ></div>

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.


Solution

  • 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:

    let dropArea = document.getElementById('dropArea');
    dropArea.addEventListener('dragover', e => e.preventDefault());
    dropArea.addEventListener('drop', function(e) {
      e.preventDefault();
      let html = e.dataTransfer.getData('text/html');
      let src = new DOMParser().parseFromString(html, "text/html")
                  .querySelector('img').src;
      console.log(src);
    });
    <img src="https://dummyimage.com/200x100/c916c9/fff.jpg" draggable="true">
    <div id="dropArea" style="height: 100px; background: dodgerblue;">Drop here</div>