Home > database >  Get src of dropped image from event target
Get src of dropped image from event target

Time:06-18

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.

CodePudding user response:

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>

CodePudding user response:

The drag and drop API in vanilla JS works just fine in React too, by saving the data inside the event when dragging starts. Use event.dataTransfer.setData to set a value, and in the drop target, event.dataTransfer.getData to retrieve it. Here's an example:

const App = () => {
    const src = "https://dummyimage.com/200x100/c916c9/fff.jpg";
    return (
        <div>
            <img
                alt="dummy-img"
                src={src}
                draggable="true"
                onDragStart={e => e.dataTransfer.setData('text/plain', src)}
            />
            <div
                onDragOver={(e) => e.preventDefault()}
                onDrop={(e) => {
                    e.preventDefault();
                    console.log(e.dataTransfer.getData('text/plain'));
                }}
            >drop here</div>
        </div>
    );
};

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

  • Related