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

드래그 앤 드롭 기능은 사용자 경험을 향상시키는 강력한 기능 중 하나입니다. 만약 요소를 드래그 앤 드롭하여 회전하는 기능을 구현하고 싶다면, Beautiful Dnd 라이브러리를 사용할 수 있습니다. 이 라이브러리는 React 기반의 드래그 앤 드롭 기능을 제공하며, 요소 회전도 쉽게 구현할 수 있습니다.

Beautiful Dnd 설치하기

먼저 Beautiful Dnd를 설치해야 합니다. 아래의 명령어를 사용하여 npm을 통해 Beautiful Dnd를 설치해주세요.

npm install react-beautiful-dnd

요소 회전 기능 구현하기

이제 Beautiful Dnd를 사용하여 요소 회전 기능을 구현해보겠습니다.

  1. Beautiful Dnd를 import 합니다.
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
  1. 회전을 하려는 요소들을 Draggable 컴포넌트로 감싸주세요.

<Draggable draggableId="item-1" index={0}>
  {(provided, snapshot) => (
    <div
      ref={provided.innerRef}
      {...provided.draggableProps}
      {...provided.dragHandleProps}
      style={{
        // 드래그 시의 스타일 변경
        ...provided.draggableProps.style,
        transform: `rotate(${snapshot.isDragging ? '45deg' : '0'})`
      }}
    >
      요소 1
    </div>
  )}
</Draggable>

  1. 요소들을 Droppable 컴포넌트로 감싸서 드롭 영역을 생성해주세요.

<Droppable droppableId="droppable">
  {(provided, snapshot) => (
    <div
      ref={provided.innerRef}
      {...provided.droppableProps}
      style={{
        // 드롭 영역의 스타일 변경
        ...provided.droppableProps.style,
        backgroundColor: snapshot.isDraggingOver ? 'lightblue' : 'white'
      }}
    >
      {/* 요소들 */}
    </div>
  )}
</Droppable>

  1. DragDropContext 컴포넌트로 Draggable과 Droppable을 감싸서 드래그 앤 드롭 기능을 활성화해주세요.
<DragDropContext onDragEnd={handleDragEnd}>
  {/* Draggable과 Droppable */}
</DragDropContext>
  1. handleDragEnd 함수를 구현하여 요소의 드래그 앤 드롭 이벤트를 처리해주세요.
const handleDragEnd = (result) => {
  // 드래그 앤 드롭 종료 시 처리할 로직 작성
};

요약

Beautiful Dnd를 사용하면 간단한 설정으로 요소의 드래그 앤 드롭 기능과 회전 기능을 구현할 수 있습니다. 위의 단계를 따라하면 손쉽게 요소 회전 기능을 적용할 수 있습니다.

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