🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Drag and Drop

React UIđŸŸĸ Free Lesson

Advertisement

Drag and Drop

React DnD, sortable lists, drag handles, and drop zones.

Overview

Drag and drop enables intuitive reordering and file upload interfaces.

Key Concepts

  • React DnD — Drag and drop for React with HTML5 backend
  • useDrag — Make elements draggable
  • useDrop — Create drop targets
  • Sortable Lists — Reorder items with drag
  • File Drops — Handle file uploads with drop zones

Code Examples

import { DndContext, closestCenter, useSensor, useSensors } from '@dnd-kit/core';
import { SortableContext, useSortable, arrayMove } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';

function SortableItem({ id, content }) {
  const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id });
  
  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  };

  return (
    <div ref={setNodeRef} style={style} {...attributes} {...listeners}>
      {content}
    </div>
  );
}

function SortableList({ items, onReorder }) {
  const sensors = useSensors(useSensor(PointerSensor));

  const handleDragEnd = (event) => {
    const { active, over } = event;
    if (active.id !== over.id) {
      const oldIndex = items.findIndex(item => item.id === active.id);
      const newIndex = items.findIndex(item => item.id === over.id);
      onReorder(arrayMove(items, oldIndex, newIndex));
    }
  };

  return (
    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
      <SortableContext items={items.map(i => i.id)}>
        {items.map(item => (
          <SortableItem key={item.id} id={item.id} content={item.content} />
        ))}
      </SortableContext>
    </DndContext>
  );
}

Practice

Build a kanban board with drag-and-drop card reordering between columns.

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement