Rajesh Saravanan
Rajesh's blog

Follow

Rajesh's blog

Follow
React Drag and Drop - JavaScript Exercise #23

React Drag and Drop - JavaScript Exercise #23

React Simple Drag and Drop Boxes Between Two Containers

Rajesh Saravanan's photo
Rajesh Saravanan
ยทMar 20, 2023ยท

5 min read

Overview

In this exercise, you will create a simple drag and drop functionality in React without using any external libraries. You will implement this functionality by creating two containers, one for draggable items and the other for dropped items.

Instructions

  1. Create two container components, one for the draggable items and one for the dropped items.

  2. Create a few draggable items within the first container. These can be simple divs with some text inside.

  3. Implement drag and drop functionality by adding onDragStart, onDragOver, onDragEnter, and onDrop event handlers to the draggable and droppable components.

  4. When the user starts dragging an item, set the item's id as the dataTransfer object's data.

  5. When a draggable item is being dragged over the droppable container, prevent the default behavior by calling event.preventDefault() and change the background color of the droppable container to indicate that it is a valid drop target.

  6. When the draggable item is dropped onto the droppable container, remove the item from the draggable container and add it to the dropped container.

  7. Update the state of the parent component to reflect the changes in the items' containers.

Bonus Requirements

  1. Add animation effects to the drag and drop functionality.

  2. Implement the functionality to allow the user to drag and drop items between multiple containers.

  3. Add the ability to delete items from the dropped container.

  4. Use local storage to persist the state of the containers, so that the state is not lost on page refresh.

Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.

So, grab a pen and paper, fire up your code editor, and get ready to dive into the React Drag and Drop exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.

Output for the Drag and Drop exercise

import React, { useState } from 'react';
import { DraggableContainer, DroppedContainer } from './containers';
import './styles.css';

function App() {
  const [availableItems, setAvailableItems] = useState([
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' },
    { id: 3, name: 'Item 3' },
    { id: 4, name: 'Item 4' },
    { id: 5, name: 'Item 5' },
  ]);
  const [droppedItems, setDroppedItems] = useState([]);

  const handleDragStart = (event, item) => {
    event.dataTransfer.setData('text/plain', JSON.stringify(item));
  };

  const handleDragOver = (event) => {
    event.preventDefault();
  };

  const handleDrop = (event) => {
    event.preventDefault();
    const data = JSON.parse(event.dataTransfer.getData('text/plain'));
    if (!droppedItems.find((item) => item.id === data.id)) {
      setDroppedItems([...droppedItems, data]);
    }
  };

  const handleRemoveItem = (item) => {
    setDroppedItems(droppedItems.filter((i) => i.id !== item.id));
  };

  return (
    <div className="app-container">
      <DraggableContainer items={availableItems} onDragStart={handleDragStart} />
      <DroppedContainer
        items={droppedItems}
        onDragOver={handleDragOver}
        onDrop={handleDrop}
        onRemoveItem={handleRemoveItem}
      />
    </div>
  );
}

export default App;
import React from 'react';

function DraggableContainer(props) {
  return (
    <div className="draggable-container">
      {props.items.map((item) => (
        <div
          key={item.id}
          className="draggable-item"
          draggable="true"
          onDragStart={(event) => props.onDragStart(event, item)}
        >
          {item.name}
        </div>
      ))}
    </div>
  );
}

function DroppedContainer(props) {
  return (
    <div
      className="dropped-container"
      onDragOver={props.onDragOver}
      onDrop={props.onDrop}
    >
      {props.items.map((item) => (
        <div key={item.id} className="dropped-item">
          {item.name}
        </div>
      ))}
    </div>
  );
}

export { DraggableContainer, DroppedContainer };
.draggable-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: center;
  width: 100%;
  height: 200px;
  border: 1px solid black;
  margin-bottom: 20px;
}

.draggable-item {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  background-color: white;
  border: 1px solid black;
  border-radius: 5px;
  margin-bottom: 10px;
  cursor: move;
}

.dropped-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: center;
  width: 100%;
  height: 200px;
  border: 1px solid black;
}

.dropped-item {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  background-color: lightgray;
  border: 1px solid black;
  border-radius: 5px;
  margin-bottom: 10px;
}

Drag and drop is a versatile user interface feature that can be used in many applications to improve the user experience. Here are some examples of applications where drag and drop can be used:

  1. File Management System: A file management system could allow users to drag and drop files between folders, move files around within a folder, or even drag and drop files onto an external storage device.

  2. Kanban Boards: A kanban board is a project management tool that allows teams to visualize their work in progress. Drag and drop can be used to move tasks from one column to another, reorder tasks within a column, or even move tasks between different boards.

  3. Image Galleries: An image gallery could allow users to drag and drop images to rearrange them or move them into different albums.

  4. Email Management System: An email management system could allow users to drag and drop emails into folders, move emails around within a folder, or even drag and drop attachments to save them to a local folder.

  5. Spreadsheet Application: A spreadsheet application could allow users to drag and drop cells to rearrange them or move them to different sheets.

These are just a few examples of how drag and drop can be used in various applications to improve the user experience and make complex tasks more intuitive and efficient.

Thanks for taking this JavaScript exercise!

I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practising and experimenting with React, and you'll be well on your way to becoming a skilled React developer!

If you have any questions or comments, feel free to reach out to me on Twitter(@rajeshtomjoe), or follow me for more updates.

And if you'd like to receive more exercise on JavaScript, be sure to subscribe to my blog.

ย 
Share this