Drag and drop dataTransfer.getData is always getting empty string

1.7k views Asked by At

I am trying do simple drag and drop functionality. I want set some data in on drag via dataTransfer.setData() and get it on drop via dataTransfer.getData() . I am always getting empty string ("").

Please check the link for reproducing example https://codesandbox.io/s/quizzical-lamport-p7cqiv?file=/src/Sample.js

drag and drop and check console

My Environment:

Browser: Chrome

OS: Windows

React UI library

1

There are 1 answers

0
Yamo93 On BEST ANSWER

You're using the wrong event. You should use the onDragStart event:

import React from "react";

class Abc extends React.Component {
  drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
  }

  allowDrop(ev) {
    ev.preventDefault();
  }

  drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    console.log("data", data);
  }
  render() {
    return (
      <>
        <div id={"some_id"} onDragStart={this.drag} draggable={true}>
          Drag Me
        </div>

        <div onDragOver={this.allowDrop} onDrop={this.drop}>
          Drop On me
        </div>
      </>
    );
  }
}

export default Abc;