본문 바로가기
React

React에서 Drag-and-Drop 기능 구현하기

by 굿센스굿 2024. 12. 17.
반응형

 

React 애플리케이션에서 사용자 경험(UX)을 향상시키는 다양한 기능 중 하나가 바로 Drag-and-Drop입니다. Drag-and-Drop은 항목을 드래그하여 다른 위치로 이동시키거나 특정 이벤트를 트리거하는 데 유용하게 사용됩니다. 이 글에서는 React에서 Drag-and-Drop 기능을 구현하는 방법을 단계별로 알아보고, 이를 활용한 실제 예제를 소개하겠습니다.


1. Drag-and-Drop의 기본 개념

Drag-and-Drop은 DOM 이벤트를 활용해 구현됩니다. HTML5 표준에서 제공하는 DragEvent 인터페이스를 사용하며, React에서는 이를 손쉽게 관리할 수 있도록 이벤트 핸들링 기능을 제공합니다. 기본적으로 Drag-and-Drop은 다음과 같은 과정을 따릅니다:

  1. 드래그 시작: 사용자가 드래그할 요소를 선택하고 이동을 시작함.
  2. 드래그 중: 요소를 이동하는 동안 다른 요소 위에 올려놓거나 이동 경로를 시각적으로 표시함.
  3. 드랍: 드래그한 요소를 특정 영역에 놓는 동작.

Drag-and-Drop을 완전히 구현하려면 onDragStart, onDragOver, onDrop 등 여러 이벤트 핸들러를 설정해야 합니다.


2. React에서 Drag-and-Drop 기본 구현

React에서는 상태 관리와 이벤트 처리의 조합으로 Drag-and-Drop을 구현할 수 있습니다. 아래는 간단한 리스트 아이템을 드래그하여 순서를 변경하는 예제입니다.

코드 예제

import React, { useState } from "react";

const DragAndDrop = () => {
  const [items, setItems] = useState(["React", "Vue", "Angular", "Svelte"]);

  const handleDragStart = (event, index) => {
    event.dataTransfer.setData("text/plain", index);
  };

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

  const handleDrop = (event, index) => {
    const draggedIndex = event.dataTransfer.getData("text/plain");
    const updatedItems = [...items];
    const [draggedItem] = updatedItems.splice(draggedIndex, 1);
    updatedItems.splice(index, 0, draggedItem);
    setItems(updatedItems);
  };

  return (
    <div>
      <h1>Drag-and-Drop 예제</h1>
      <ul>
        {items.map((item, index) => (
          <li
            key={index}
            draggable
            onDragStart={(event) => handleDragStart(event, index)}
            onDragOver={handleDragOver}
            onDrop={(event) => handleDrop(event, index)}
            style={{
              padding: "10px",
              margin: "5px",
              border: "1px solid #ccc",
              cursor: "move",
              backgroundColor: "#f9f9f9",
            }}
          >
            {item}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default DragAndDrop;

코드 설명

  1. useState로 데이터 관리: items 배열은 리스트 항목을 저장하며, 상태 변경을 통해 Drag-and-Drop의 결과를 반영합니다.
  2. 드래그 시작: onDragStart 이벤트 핸들러에서 dataTransfer 객체를 활용해 드래그된 항목의 인덱스를 저장합니다.
  3. 드래그 허용: onDragOver 이벤트 핸들러에서 기본 동작을 막아 드랍을 허용합니다.
  4. 드랍 처리: onDrop 이벤트 핸들러에서 드래그된 항목의 데이터를 가져와 리스트를 재배치합니다.

3. React DnD 라이브러리 활용하기

복잡한 Drag-and-Drop 기능을 구현해야 한다면 React DnD와 같은 라이브러리를 사용하는 것이 좋습니다. React DnD는 높은 유연성과 강력한 API를 제공하며, 드래그 가능한 다양한 유형의 컴포넌트와 사용자 정의 로직을 지원합니다.

React DnD 설치

React DnD를 사용하려면 다음 패키지를 설치하세요.

npm install react-dnd react-dnd-html5-backend

간단한 React DnD 예제

React DnD를 사용해 간단한 예제를 만들어 보겠습니다.

import React from "react";
import { DndProvider, useDrag, useDrop } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";

const ItemType = {
  ITEM: "item",
};

const DraggableItem = ({ id, text, moveItem }) => {
  const [, ref] = useDrag({
    type: ItemType.ITEM,
    item: { id },
  });

  const [, drop] = useDrop({
    accept: ItemType.ITEM,
    drop: (draggedItem) => moveItem(draggedItem.id, id),
  });

  return (
    <div ref={(node) => ref(drop(node))} style={{ padding: "10px", border: "1px solid black", margin: "5px", backgroundColor: "#f0f0f0" }}>
      {text}
    </div>
  );
};

const DragAndDropWithLibrary = () => {
  const [items, setItems] = React.useState([
    { id: 1, text: "React" },
    { id: 2, text: "Vue" },
    { id: 3, text: "Angular" },
  ]);

  const moveItem = (draggedId, targetId) => {
    const draggedIndex = items.findIndex((item) => item.id === draggedId);
    const targetIndex = items.findIndex((item) => item.id === targetId);
    const updatedItems = [...items];
    const [draggedItem] = updatedItems.splice(draggedIndex, 1);
    updatedItems.splice(targetIndex, 0, draggedItem);
    setItems(updatedItems);
  };

  return (
    <DndProvider backend={HTML5Backend}>
      <h1>React DnD 예제</h1>
      {items.map((item) => (
        <DraggableItem key={item.id} id={item.id} text={item.text} moveItem={moveItem} />
      ))}
    </DndProvider>
  );
};

export default DragAndDropWithLibrary;

4. Drag-and-Drop 활용 사례

  1. 파일 업로드: 사용자가 파일을 특정 영역으로 드래그하면 업로드 프로세스를 트리거.
  2. 보드 애플리케이션: Trello나 Jira와 같은 작업 관리 도구에서 카드의 위치를 드래그하여 변경.
  3. 이미지 정렬: 갤러리 애플리케이션에서 이미지 순서를 재배치.

5. 결론

React에서 Drag-and-Drop 기능을 구현하는 방법은 간단한 기본 기능부터 React DnD와 같은 강력한 라이브러리 활용까지 다양합니다. 위에서 다룬 예제를 시작점으로 삼아, 여러분의 프로젝트에 적합한 Drag-and-Drop 기능을 설계해 보세요.

React로 더욱 직관적이고 사용하기 편리한 UX를 구축할 수 있을 것입니다!

반응형