[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 다중 선택하기

이 글에서는 Beautiful Dnd 라이브러리를 사용하여 드래그 앤 드롭으로 다중 선택을 구현하는 방법을 소개하겠습니다.

Beautiful Dnd란?

Beautiful Dnd는 React에서 드래그 앤 드롭 기능을 구현하기 위한 라이브러리입니다. 이 라이브러리는 사용자가 아이템을 드래그하여 다른 위치로 이동시킬 수 있게 해주며, 다양한 드래그 앤 드롭 기능을 제공합니다.

다중 선택 구현하기

Beautiful Dnd를 사용하여 다중 선택을 구현하기 위해서는 몇 가지 단계를 거쳐야 합니다.

  1. Beautiful Dnd 패키지를 설치합니다.
npm install react-beautiful-dnd
  1. Beautiful Dnd를 사용하기 위해 필요한 컴포넌트와 Hooks를 import 합니다.
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
  1. 다중 선택을 지원하기 위해 아이템의 선택 상태를 관리할 수 있는 상태 변수와 함수를 정의합니다.
const [selectedItems, setSelectedItems] = useState([]);
  1. 선택된 아이템을 업데이트하는 함수를 작성합니다.
const handleItemSelected = (itemId) => {
  if (selectedItems.includes(itemId)) {
    setSelectedItems(selectedItems.filter((id) => id !== itemId));
  } else {
    setSelectedItems([...selectedItems, itemId]);
  }
};
  1. Draggable 컴포넌트의 isDragDisabled 속성을 이용하여 선택 상태에 따라 드래그 할 수 없도록 지정합니다.
<Draggable
  draggableId={item.id}
  index={index}
  isDragDisabled={selectedItems.includes(item.id)}
>
...
</Draggable>
  1. 사용자가 아이템을 선택하거나 드래그하여 위치를 변경할 때마다 선택 상태를 업데이트하기 위해 onDragStart, onDragUpdate, onDragEnd 이벤트 핸들러를 구현합니다.
const onDragEnd = (result) => {
  const { destination, draggableId } = result;
  
  if (!destination) {
    return;
  }

  setSelectedItems([]);
  
  // 아이템 이동 로직 구현
  ...
};
  1. DragDropContext와 Droppable 컴포넌트로 아이템을 래핑하고, Draggable 컴포넌트 안에서 아이템을 렌더링합니다.
<DragDropContext onDragEnd={onDragEnd}>
  <Droppable droppableId="droppable">
    {(provided) => (
      <div {...provided.droppableProps} ref={provided.innerRef}>
        {items.map((item, index) => (
          <Draggable
            draggableId={item.id}
            index={index}
            isDragDisabled={selectedItems.includes(item.id)}
            key={item.id}
          >
            {(provided) => (
              <div
                ref={provided.innerRef}
                {...provided.draggableProps}
                {...provided.dragHandleProps}
                onClick={() => handleItemSelected(item.id)}
              >
                {item.content}
              </div>
            )}
          </Draggable>
        ))}
        {provided.placeholder}
      </div>
    )}
  </Droppable>
</DragDropContext>

이제 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 다중 선택을 구현할 수 있습니다. 위의 단계를 따라하면 원하는 기능을 쉽게 구현할 수 있을 것입니다.

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