Joel's Thoughts

Draftjs Error Fix On Datatransfer Object While Handling Custom Drop Event

January 30, 2019

Recently, I am working on a React project that was mainly using Draftjs editor. It involves adding a customized drag and drop functionality using a target draggable element. On the draggable’s “onDragStart” event, I need to set data using DataTransfer API. The error occurs on Draftjs if I don’t set a text property. Here’s a discussion about that error on Github, https://github.com/facebook/draft-js/issues/494.


To translate in code, here’s how it looks like.

   import Editor from 'draft-js-plugins-editor';

   class MyDragDropEditor extends React.Component {
      // ... some code here

      handleDragStart(event) {
          // needs to set text property so it won't throw an error
          event.dataTransfer.setData('text', 'some text so it will not throw an error');
          event.dataTransfer.setData('block', 'my data block');
          // more code .....
      }

      render () {
          return (
              <div>
                  <Editor
                    key="editor"
                  />
                  <span
                    draggable
                    key="draggable"
                    onDragStart={handleDragStart}
                  >
                  Drag Handle
                  </span>
              </div>
          );
      }
   }

   export default MyDragDropEditor;

You might think setting an empty string as text property will fix the issue. However, it introduced extra unwanted behaviors on the Editor. Been scratching my head for a while and finally figured out a solid solution. Turns out the solution is to set Draftjs “handleDrop” props to return true or string “handled”. By doing this, we are telling Draftjs that we want to handle “onDrop” event on our own.


Here’s how the above code looks after implementing the solution.

      // ... more code before

       render () {
           return (
               <div>
                   <Editor
                     key="editor"
                     handleDrop={() => "handled"}
                   />
                   <span
                     draggable
                     key="draggable"
                     onDragStart={handleDragStart}
                   >
                   Drag Handle
                   </span>
               </div>
           );
       }
    }

If you have another solution for this issue, please let me know. Thanks for reading!









  • About
  • Search
  • Resume
  • Powered by Jekyll using the Trio theme