드래그 앤 드롭 기능은 웹 애플리케이션에서 매우 유용한 기능 중 하나입니다. 사용자가 요소를 드래그하여 다른 위치로 이동할 수 있게 해주는 것이죠. Beautiful Dnd는 이러한 드래그 앤 드롭 기능을 쉽게 구현할 수 있는 라이브러리입니다. 이번 블로그에서는 Beautiful Dnd를 사용하여 요소 이동 경로를 애니메이션화하는 방법에 대해 알아보겠습니다.
1. Beautiful Dnd 설치하기
먼저 Beautiful Dnd를 설치해야 합니다. npm을 사용한다면 다음 명령어를 사용하여 설치할 수 있습니다.
npm install react-beautiful-dnd
yarn을 사용한다면 다음 명령어를 사용합니다.
yarn add react-beautiful-dnd
2. 드래그 앤 드롭 컴포넌트 만들기
드래그 앤 드롭을 구현하려면 Beautiful Dnd의 DragDropContext 컴포넌트와 draggable, droppable 컴포넌트를 사용해야 합니다.
import React from "react";
import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd";
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [
{ id: "1", content: "Item 1" },
{ id: "2", content: "Item 2" },
{ id: "3", content: "Item 3" },
],
};
this.onDragEnd = this.onDragEnd.bind(this);
}
onDragEnd(result) {
if (!result.destination) {
return;
}
const items = Array.from(this.state.items);
const [reorderedItem] = items.splice(result.source.index, 1);
items.splice(result.destination.index, 0, reorderedItem);
this.setState({
items,
});
}
render() {
return (
<DragDropContext onDragEnd={this.onDragEnd}>
<Droppable droppableId="droppable">
{(provided, snapshot) => (
<div ref={provided.innerRef} {...provided.droppableProps}>
{this.state.items.map((item, index) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided, snapshot) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
<p>{item.content}</p>
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
);
}
}
export default MyComponent;
위 코드에서는 items 배열을 사용하여 드래그 앤 드롭할 요소들을 정의하고, onDragEnd 함수에서 드래그 앤 드롭 이벤트가 종료되었을 때의 동작을 정의하고 있습니다. 드래그할 요소를 정의하는 Draggable 컴포넌트와 드롭할 영역을 정의하는 Droppable 컴포넌트를 사용하여 드래그 앤 드롭 기능을 구현하고 있습니다.
3. 요소 이동 경로 애니메이션화하기
이제 요소가 이동할 때 애니메이션을 적용해보겠습니다. Beautiful Dnd는 item들이 이동하는 동안 CSS transition을 사용하여 애니메이션 효과를 적용할 수 있습니다. 이를 위해 draggable 컴포넌트에 transition 속성을 추가하면 됩니다.
.draggable-item {
transition: transform 0.2s ease;
}
위와 같이 CSS 스타일을 추가해줍니다. 그리고 draggable 컴포넌트의 div 엘리먼트에 draggable-item
클래스를 추가합니다.
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided, snapshot) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
className="draggable-item"
>
<p>{item.content}</p>
</div>
)}
</Draggable>
이제 요소를 드래그하여 이동할 때, 애니메이션 효과가 적용되면서 부드럽게 이동하는 것을 확인할 수 있습니다.
결론
Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소를 이동 경로를 애니메이션화할 수 있습니다. 위에서 살펴본 예제 코드를 참고하여 자신의 프로젝트에 적용해보세요. Beautiful Dnd에 대한 자세한 내용은 공식 문서를 참고하시기 바랍니다.
참고 문서: