[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소 정렬하기

드래그 앤 드롭은 사용자가 원하는 대로 요소를 이동하고 재정렬할 수 있는 편리한 기능입니다. 여기서는 Beautiful Dnd 라이브러리를 사용하여 자바스크립트에서 드래그 앤 드롭을 구현하는 방법을 알아보겠습니다.

Beautiful Dnd란?

Beautiful Dnd는 React를 기반으로한 드래그 앤 드롭 라이브러리입니다. 이를 사용하면 원하는 요소를 쉽게 이동하고 재정렬할 수 있습니다. Beautiful Dnd는 우수한 성능을 제공하며, 화면 스크롤과의 상호작용, 드래그 스타일링 등 다양한 기능을 제공합니다.

설치 및 설정

먼저, Beautiful Dnd를 설치해야 합니다. npm을 이용하여 설치하는 방법은 다음과 같습니다.

npm install react-beautiful-dnd

설치가 완료되었으면, 해당 모듈을 가져와서 사용할 수 있습니다. React 프로젝트에서 다음과 같이 라이브러리를 import합니다.

import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';

여기서 DragDropContext는 드래그 앤 드롭을 사용할 컴포넌트를 감싸는 컨테이너입니다. Droppable은 재정렬하고자 하는 요소를 감싸는 컴포넌트이고, Draggable은 실제로 드래그 가능한 요소입니다.

요소 정렬하기

Beautiful Dnd를 사용하여 요소를 정렬하기 위해서는 몇 가지 단계를 거쳐야 합니다.

  1. 컨테이너와 드롭 영역 생성하기: DragDropContext 컴포넌트를 이용하여 드래그 앤 드롭을 적용할 컨테이너를 생성합니다. 그리고 재정렬하고자 하는 요소를 감싸는 Droppable 컴포넌트를 생성합니다.
<DragDropContext>
  <Droppable droppableId="droppable">
    {(provided, snapshot) => (
      <div
        ref={provided.innerRef}
        {...provided.droppableProps}
      >
        {/* 재정렬하고자 하는 요소들 */}
      </div>
    )}
  </Droppable>
</DragDropContext>
  1. 드래그 가능한 요소 생성하기: 재정렬하고자 하는 개별 요소에 대해서는 Draggable 컴포넌트를 사용합니다. 이 컴포넌트는 draggableId와 해당 요소의 내용을 전달 받습니다.
<Droppable droppableId="droppable">
  {(provided, snapshot) => (
    <div
      ref={provided.innerRef}
      {...provided.droppableProps}
    >
      {items.map((item, index) => (
        <Draggable
          key={item.id}
          draggableId={item.id}
          index={index}
        >
          {(provided, snapshot) => (
            <div
              ref={provided.innerRef}
              {...provided.draggableProps}
              {...provided.dragHandleProps}
            >
              {item.content}
            </div>
          )}
        </Draggable>
      ))}
      {provided.placeholder}
    </div>
  )}
</Droppable>
  1. 요소 재정렬 로직 구현하기: onDragEnd 이벤트 핸들러를 통해 요소의 재정렬 로직을 구현할 수 있습니다.
<DragDropContext onDragEnd={handleDragEnd}>
const handleDragEnd = result => {
  const { destination, source } = result;
  
  if (!destination) {
    return;
  }
  
  // 요소의 위치 이동
  const items = Array.from(this.state.items);
  const [removed] = items.splice(source.index, 1);
  items.splice(destination.index, 0, removed);
  
  // 재정렬된 요소 저장
  this.setState({ items });
}

이렇게 구현하면 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소를 정렬할 수 있습니다.

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