Drag and drop with React and native HTML5

In this post I would like to show how you can implement a simple drag and drop features using the native HTML5 drag and drop events and React (but clearly you could use anything you like). I have seen a number of feature-packed libraries that surely accomplish everything you can dream of but this is how I you can get it done in the simplest way.

Codesandbox

Here is the Codesandbox for this demo. For some reason the drag and drop feature seems to not be working inside this iframe, so maybe just open it in a new tab.

CodeSandbox

How does it work

In order to accomplish the drag and drop, we make use of a number of native events implemented in Card.js and Dropzone.js. In Card.js you should pay attention to the following handleDragStart function, which is triggered when you start dragging. It will save some data using the native HTML5 method dataTransfer.setData.

In Dropzone.js you will find a series of functions that are triggered when entering, leaving, hovering a dropzone, plus the handleDrop function, triggered when releasing an element over the dropzone. When this happens, the following function is used to retrieve the saved data, set the dragging state to false, and call the function that will take care of changing the status of the card. Please note that props.status comes down from App.js.

Warning: I did not implement reordering of the cards, too much work ???? but I suppose something can be hacked together by using the APIs shown here, by getting the initial order and the order of the card you are dropping onto.

Leave a Reply

Your email address will not be published. Required fields are marked *