Categories
React Projects

Create a Drag and Drop App with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a drag and drop app with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app drag-and-drop

with NPM to create our React project.

Create the Drag and Drop App

To create the drag and drop app, we write:

import React, { useState } from "react";

export default function App() {
  const [origin, setOrigin] = useState(["apple", "orange", "grape"]);
  const [target, setTarget] = useState([]);

  const drag = (ev, text) => {
    ev.dataTransfer.setData("text", text);
  };

  const drop = (ev) => {
    const text = ev.dataTransfer.getData("text");
    const index = origin.findIndex((o) => o === text);
    setOrigin((origin) => origin.filter((_, i) => i !== index));
    setTarget((target) => [...target, text]);
  };

  return (
    <div>
      <style>
        {`
          .draggable {
            border: 1px solid black;
            margin-right: 5px;
          }

          #target {
            border: 1px solid black;
            width: 95vw;
            height: 100px;
            padding: 5px;
          }
          `}
      </style>
      <h2>Draggable Elements</h2>
      {origin.map((o) => {
        return (
          <div
            className="draggable"
            draggable
            onDragStart={(e) => drag(e, o)}
            key={o}
            onClick={(e) => e.stopPropagation()}
          >
            {o}
          </div>
        );
      })}

      <h2>Target</h2>
      <div id="target" onDragOver={(e) => e.preventDefault()} onDrop={drop}>
        {target.map((t) => {
          return (
            <div className="draggable" key={t}>
              {t}
            </div>
          );
        })}
      </div>
    </div>
  );
}

We have the origin array state that’s rendered into items that we can drag and drop.

The target array has the dropped items.

Next, we have the drag function that calls ev.dataTransfer.setData to set the data that we want to drag.

The first argument is the key that we can use to get the data.

And the 2nd argument is the data for the corresponding key.

Next, we have the drop method that calls ev.dataTransfer.getData with the key to get the data.

Then we call origin.findIndex to find the index for the data.

Next, we remove the item from the origin with setOrigin called with a callback that returns a copy of the origin array without the index .

And we call setTarget with a callback that returns a copy of the target array with the text value appended to it.

Below that, we have some styles for the drag and drop items and containers.

And below that, we render the origin items.

To make them draggable, we add the draggable prop.

Then we add the onDragStart prop and set a function that calls drag .

onClick is set to a function that calls e.stopPropagation to stop the click event from bubbling to parent and ancestor items.

And below that, we render the target items with the onDragOver and onDrop props.

onDragOver is set to a function that e.preventDefault() so we can do the dropping.

And onDrop is set to drop to let us move data from origin to target .

Conclusion

We can create a drag and drop app easily with React and JavaScript.

Leave a Reply

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