[javascript] Beautiful Dnd를 사용하여 트리 구조 항목 드래그 앤 드롭 구현하기

드래그 앤 드롭은 사용자가 항목을 움직여서 다른 위치로 이동할 수 있는 기능을 말합니다. 트리 구조를 갖는 항목들 중에서도 이 기능을 구현하려면 라이브러리를 사용하는 것이 효율적일 수 있습니다. 이번 블로그 포스트에서는 Beautiful Dnd 라이브러리를 사용하여 트리 구조 항목의 드래그 앤 드롭을 구현하는 방법에 대해 소개하겠습니다.

Beautiful Dnd란?

Beautiful Dnd는 React를 기반으로 한 드래그 앤 드롭 라이브러리입니다. 이 라이브러리를 사용하면 원하는 형태의 드래그 앤 드롭 인터페이스를 쉽게 구현할 수 있습니다. Beautiful Dnd는 표준 HTML5 드래그 앤 드롭 API를 기반으로 작동하며, 유연하고 성능이 우수합니다.

Beautiful Dnd 설치하기

먼저 Beautiful Dnd를 설치해야 합니다. npm을 사용한다면 아래의 명령어를 사용하여 설치할 수 있습니다.

npm install react-beautiful-dnd

트리 구조 항목 드래그 앤 드롭 구현하기

  1. 먼저, react-beautiful-dnd에서 제공하는 DragDropContext 컴포넌트를 import 해줍니다.
import { DragDropContext } from 'react-beautiful-dnd';
  1. 항목들의 리스트를 렌더링하는 컴포넌트를 생성합니다. 이 예시에서는 TreeList라는 컴포넌트를 사용합니다.
function TreeList() {
  return (
    <div>
      {treeData.map((item, index) => (
        <Draggable key={item.id} draggableId={item.id} index={index}>
          {(provided) => (
            <div
              ref={provided.innerRef}
              {...provided.draggableProps}
              {...provided.dragHandleProps}
              className="tree-item"
            >
              {item.name}
            </div>
          )}
        </Draggable>
      ))}
    </div>
  );
}
  1. DragDropContext 컴포넌트로 전체 앱을 감싸줍니다.
function App() {
  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <TreeList />
    </DragDropContext>
  );
}
  1. handleDragEnd 함수를 작성하여 드래그 앤 드롭 완료 후의 동작을 지정합니다.
function handleDragEnd(result) {
  // 드래그 앤 드롭이 유효한 경우
  if (result.destination) {
    // 항목 위치 변경
    const items = Array.from(treeData);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);

    // 변경된 항목 리스트 업데이트
    setTreeData(items);
  }
}

이제 Beautiful Dnd를 사용하여 트리 구조 항목의 드래그 앤 드롭을 구현할 수 있습니다. 위의 코드를 참고하여 자신의 프로젝트에 맞게 수정하고 적용해보세요.

참고 자료