[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 트리뷰 만들기

이번 포스팅에서는 React를 사용하여 Beautiful Dnd 라이브러리를 이용해 드래그 앤 드롭으로 트리뷰(Tree View)를 만드는 방법을 알아보겠습니다.

Beautiful Dnd란?

Beautiful Dnd는 Atlassian이 개발한 React용 드래그 앤 드롭 라이브러리입니다. 이 라이브러리를 사용하면 간단한 설정만으로 다양한 컴포넌트에 드래그 앤 드롭 기능을 추가할 수 있습니다.

프로젝트 설정

첫 번째로, 프로젝트를 생성하고 필요한 패키지들을 설치해줍니다. 아래 명령어를 터미널에 입력합니다.

npx create-react-app drag-and-drop-treeview
cd drag-and-drop-treeview

그리고 Beautiful Dnd 패키지를 설치합니다.

npm install react-beautiful-dnd

트리뷰 컴포넌트 생성

다음으로, src 폴더 안에 TreeView.jsx 파일을 생성하고 아래의 코드를 작성합니다.

import React, { useState } from "react";
import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd";

const TreeView = () => {
  const [items, setItems] = useState([
    { id: "item-1", title: "Item 1" },
    { id: "item-2", title: "Item 2" },
    { id: "item-3", title: "Item 3" }
  ]);

  const handleDragEnd = (result) => {
    if (!result.destination) return;

    const newItems = Array.from(items);
    const [reorderedItem] = newItems.splice(result.source.index, 1);
    newItems.splice(result.destination.index, 0, reorderedItem);

    setItems(newItems);
  };

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <Droppable droppableId="treeview">
        {(provided) => (
          <ul {...provided.droppableProps} ref={provided.innerRef}>
            {items.map((item, index) => (
              <Draggable key={item.id} draggableId={item.id} index={index}>
                {(provided) => (
                  <li
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                    ref={provided.innerRef}
                  >
                    {item.title}
                  </li>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </ul>
        )}
      </Droppable>
    </DragDropContext>
  );
};

export default TreeView;

위 코드에서는 TreeView 컴포넌트를 작성하고, items 상태를 이용해 표시할 아이템들의 목록을 관리합니다. DragDropContextDroppable 컴포넌트로 드래그 앤 드롭 기능을 적용하고, Draggable 컴포넌트로 각 아이템을 드래그할 수 있는 요소로 만들었습니다.

드래그 앤 드롭 작업의 결과는 handleDragEnd 함수에서 처리하고, 그 결과를 기반으로 아이템 목록을 업데이트합니다.

트리뷰 컴포넌트 사용

마지막으로, src/App.js 파일에서 아래와 같이 TreeView 컴포넌트를 사용합니다.

import React from "react";
import TreeView from "./TreeView";

const App = () => {
  return (
    <div>
      <h1>드래그  드롭 트리뷰</h1>
      <TreeView />
    </div>
  );
};

export default App;

이제 npm start 명령어로 앱을 실행하면 드래그 앤 드롭 트리뷰가 제대로 동작하는 것을 확인할 수 있습니다.

마무리

위에서는 Beautiful Dnd를 사용하여 React에서 드래그 앤 드롭으로 트리뷰를 만드는 방법에 대해 살펴보았습니다. Beautiful Dnd는 다양한 컴포넌트에 적용할 수 있으며, 유연한 기능을 제공합니다. 본 포스팅을 참고하여 프로젝트에 적용하여 보세요.

더 자세한 내용은 Beautiful Dnd 문서를 참고하시기 바랍니다.