드래그 앤 드롭 기능은 사용자가 요소를 쉽게 이동하고 정렬할 수 있는 인터페이스를 제공하는 데 도움이 됩니다. React 라이브러리에서는 Beautiful Dnd 라이브러리를 사용하여 간단하게 구현할 수 있습니다. 이번 블로그 포스트에서는 Beautiful Dnd를 사용하여 요소를 드래그 앤 드롭으로 회전시키는 방법을 알아보겠습니다.
Beautiful Dnd 설치하기
먼저 Beautiful Dnd를 설치해야 합니다. 다음 명령어를 사용하여 패키지를 설치합니다:
npm install react-beautiful-dnd
Beautiful Dnd 사용하기
Beautiful Dnd를 사용하기 위해 먼저 DragDropContext
, Droppable
, Draggable
컴포넌트를 import 합니다:
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
다음으로, 요소들을 감싸는 Droppable
컴포넌트를 생성합니다. 이 컴포넌트는 드롭 영역을 정의하는 역할을 합니다. 요소들은 Draggable
컴포넌트로 래핑되어 드래그 가능하게 만들어집니다. 예를 들어, 다음과 같은 코드를 사용하여 드롭 영역과 드래그 가능한 요소를 만들 수 있습니다:
<DragDropContext onDragEnd={handleDragEnd}>
<Droppable droppableId="elements">
{(provided) => (
<div ref={provided.innerRef} {...provided.droppableProps}>
{elements.map((element, index) => (
<Draggable key={element.id} draggableId={element.id} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{/* 요소 컨텐츠 */}
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
위 코드에서 elements
는 드래그 앤 드롭으로 회전시키고자 하는 요소들의 배열입니다. handleDragEnd
함수는 드래그가 끝났을 때 실행될 콜백 함수를 정의합니다.
요소 회전하기
요소를 회전시키기 위해서는 handleDragEnd
함수를 구현해야 합니다. 이 함수는 드랍이 끝났을 때 호출되며, 드래그한 요소의 위치 정보를 제공받습니다. 아래 예시 코드는 요소를 회전시키는 handleDragEnd
함수의 구현 예시입니다:
const handleDragEnd = (result) => {
// 드래그한 요소의 시작 인덱스와 끝 인덱스 가져오기
const { source, destination } = result;
if (!destination) return;
// 요소를 회전시키기 위해 source 인덱스와 destination 인덱스의 요소를 swap 합니다.
const updatedElements = [...elements];
const [removed] = updatedElements.splice(source.index, 1);
updatedElements.splice(destination.index, 0, removed);
// 회전된 요소들을 업데이트합니다.
setElements(updatedElements);
};
위 코드에서 elements
는 현재 회전시킨 요소들의 배열을 나타냅니다. source.index
와 destination.index
를 사용하여 요소를 회전시킬 방향을 결정하고 배열을 업데이트합니다.
결론
제가 위에서 소개한 방법을 사용하면 Beautiful Dnd를 통해 요소를 드래그 앤 드롭으로 회전시킬 수 있습니다. Beautiful Dnd는 다양한 드래그 앤 드롭 기능을 제공하기 때문에 다른 유형의 인터랙티브한 인터페이스를 구현할 때도 유용하게 사용할 수 있습니다.
더 자세한 내용은 Beautiful Dnd의 공식 문서를 참조하시기 바랍니다.