[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소 스냅 지원하기

이번에는 Beautiful Dnd 라이브러리를 사용하여 드래그 앤 드롭으로 요소를 스냅(Snap) 지원하는 방법에 대해서 알아보겠습니다.

Beautiful Dnd란?

Beautiful Dnd는 React 기반의 드래그 앤 드롭 라이브러리로, 사용자 친화적인 인터페이스와 매끄러운 애니메이션을 제공합니다. 이 라이브러리를 사용하면 웹 애플리케이션에서 요소들을 쉽게 드래그 앤 드롭으로 재정렬할 수 있습니다.

설치

먼저 Beautiful Dnd를 설치해야 합니다. 다음 명령어를 사용하여 npm으로 라이브러리를 설치합니다.

npm install react-beautiful-dnd

사용 방법

먼저, Beautiful Dnd를 사용하려는 React 컴포넌트에서 DragDropContext, Droppable, Draggable 컴포넌트를 import 해야 합니다.

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

DragDropContext 컴포넌트는 드래그 앤 드롭을 관리해주는 컴포넌트입니다. 다음과 같이 사용합니다.

<DragDropContext onDragEnd={handleDragEnd}>
  {/* 드래그 앤 드롭을 사용할 영역 */}
</DragDropContext>

Droppable 컴포넌트는 드래그 앤 드롭 가능한 영역을 정의하는 컴포넌트입니다. Draggable 컴포넌트는 드래그 앤 드롭 가능한 요소를 정의하는 컴포넌트입니다.

<DragDropContext onDragEnd={handleDragEnd}>
  <Droppable droppableId="droppable">
    {(provided) => (
      <div {...provided.droppableProps} ref={provided.innerRef}>
        {items.map((item, index) => (
          <Draggable key={item.id} draggableId={item.id} index={index}>
            {(provided) => (
              <div
                ref={provided.innerRef}
                {...provided.draggableProps}
                {...provided.dragHandleProps}
              >
                {/* 드래그 앤 드롭 요소 내용 */}
              </div>
            )}
          </Draggable>
        ))}
        {provided.placeholder}
      </div>
    )}
  </Droppable>
</DragDropContext>

위의 예시에서 items는 드래그 앤 드롭할 대상 요소들을 담고 있는 배열입니다. droppableIdDroppable 컴포넌트의 고유 ID입니다.

Draggable 컴포넌트 내부에서 provided.draggableProps는 드래그 가능한 요소에 적용해야 하는 props이고, provided.dragHandleProps는 드래그 헨들에 적용해야 하는 props입니다.

스냅(Snap) 지원하기

요소 스냅을 지원하기 위해서는 Droppable 컴포넌트에 direction prop을 추가하면 됩니다. direction은 요소가 드롭될 때 스냅할 수 있는 방향을 지정합니다. 예를 들어, 수평 방향으로 스냅하고 싶다면 direction'horizontal'로 설정하면 됩니다.

<Droppable droppableId="droppable" direction="horizontal">
  {/* ... */}
</Droppable>

위와 같이 설정하면 드롭 가능한 요소들이 수평 방향으로 스냅하게 됩니다.

정리

Beautiful Dnd를 사용하면 웹 애플리케이션에서 쉽게 드래그 앤 드롭 기능을 구현할 수 있습니다. 이 라이브러리를 사용하여 요소 스냅을 지원하는 방법에 대해서 간단하게 알아보았습니다. Beautiful Dnd 공식 문서에서 더 자세한 내용을 확인할 수 있습니다.

참고자료: