[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소 회전 가능성 제한하기

Beautiful Dnd는 React 기반의 드래그 앤 드롭 라이브러리로, 사용자가 요소를 드래그하여 다른 위치로 이동시킬 수 있도록 도와줍니다. 이 글에서는 Beautiful Dnd를 사용하여 요소를 드래그 앤 드롭하고, 회전 가능성을 제한하는 방법을 알아보겠습니다.

Beautiful Dnd 설치 및 설정

먼저, Beautiful Dnd를 설치하기 위해 npm을 사용합니다. 다음 명령을 실행하여 Beautiful Dnd를 설치합니다.

npm install react-beautiful-dnd

Beautiful Dnd를 사용하기 위해 DragDropContext, Droppable, Draggable 컴포넌트를 import합니다.

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

이제 Beautiful Dnd를 사용하여 드래그 앤 드롭을 구현할 준비가 되었습니다.

드래그 앤 드롭 요소 회전 기능 추가하기

회전 가능성을 제한하기 위해서는 드래그 앤 드롭 요소를 회전시킨 후, 회전된 각도를 확인하여 제한을 적용해야 합니다.

Beautiful Dnd의 Draggable 컴포넌트를 사용하여 드래그 앤 드롭 요소를 구현합니다. 이 때, onBeforeCapture 콜백을 사용하여 회전 가능성을 제한하는 로직을 추가합니다.


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

const App = () => {
  const [items, setItems] = useState([
    { id: 'item-1', content: '요소 1', angle: 0 },
    { id: 'item-2', content: '요소 2', angle: 0 },
    { id: 'item-3', content: '요소 3', angle: 0 }
  ]);

  const handleDragEnd = (result) => {
    // 드래그 앤 드롭된 요소의 위치 변경 로직
  };

  const handleBeforeCapture = (drag) => {
    const { draggableId } = drag;
    const item = items.find((item) => item.id === draggableId);

    if (item.angle !== 0) {
      // 회전된 요소의 드래그 앤 드롭을 막음
    }
  };

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <Droppable droppableId="droppable">
        {(provided) => (
          <div ref={provided.innerRef} {...provided.droppableProps}>
            {items.map((item, index) => (
              <Draggable key={item.id} draggableId={item.id} index={index} {...item}>
                {(provided) => (
                  <div
                    ref={provided.innerRef}
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                    style={{ transform: `rotate(${item.angle}deg)` }}
                  >
                    {item.content}
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  );
};

export default App;

위 코드에서 handleBeforeCapture 콜백 함수에서 회전된 요소의 드래그 앤 드롭을 막도록 제한을 적용하였습니다. item.angle은 요소의 회전 각도를 나타내는 값으로, 유효한 각도인 경우에만 드래그 앤 드롭을 허용하도록 설정하였습니다.

이제 Beautiful Dnd를 사용하여 드래그 앤 드롭할 때, 요소 회전 기능을 제한하는 방법을 알아보았습니다. 필요에 따라 해당 코드를 수정하여 원하는 제한 로직을 구현할 수 있습니다.

참고 자료