[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭 이벤트 처리하기
드래그 앤 드롭(Drag and drop)은 사용자 인터페이스(UI) 요소를 마우스로 클릭하여 이동시키는 기능을 의미합니다. 이러한 기능을 구현하려면 이벤트 처리 및 DOM 조작이 필요합니다.
이번에는 Beautiful Dnd 라이브러리를 사용하여 드래그 앤 드롭 이벤트를 처리하는 방법을 알아보겠습니다. Beautiful Dnd는 React 기반의 라이브러리로, 직관적인 API와 사용하기 쉬운 UI 컴포넌트를 제공합니다.
Beautiful Dnd 설치하기
먼저 Beautiful Dnd를 설치해야합니다. 다음 명령을 사용하여 npm으로 Beautiful Dnd를 설치할 수 있습니다.
npm install react-beautiful-dnd
드래그 앤 드롭 컴포넌트 만들기
Beautiful Dnd를 사용하여 드래그 앤 드롭을 구현하기 위해 컴포넌트를 만들어야합니다. 예를 들어, 리스트 아이템을 드래그 앤 드롭하여 순서를 변경하는 컴포넌트를 만들어보겠습니다.
import React from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
const items = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];
const App = () => {
const handleDragEnd = (result) => {
// 드래그 앤 드롭 완료시 실행될 콜백 함수
// 이곳에서 아이템의 순서를 변경해줄 수 있습니다.
if (!result.destination) return; // 드롭되지 않은 경우
const newItems = Array.from(items);
const [removed] = newItems.splice(result.source.index, 1);
newItems.splice(result.destination.index, 0, removed);
// 변경된 순서의 아이템들을 업데이트합니다.
// 이후에는 업데이트된 순서에 따라 화면을 다시 렌더링합니다.
// 예를 들어, 데이터베이스에 업데이트 요청을 보낼 수도 있습니다.
};
return (
<DragDropContext onDragEnd={handleDragEnd}>
<Droppable droppableId="droppable">
{(provided) => (
<div
{...provided.droppableProps}
ref={provided.innerRef}
>
{items.map((item, index) => (
<Draggable key={item} draggableId={item} index={index}>
{(provided) => (
<div
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
>
{item}
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
);
};
export default App;
위 예제에서, DragDropContext
컴포넌트는 드래그 앤 드롭 이벤트를 관리하고, Droppable
컴포넌트는 드롭 가능한 영역을 나타냅니다. Draggable
컴포넌트는 드래그 가능한 아이템을 나타냅니다.
결론
Beautiful Dnd를 사용하면 간단하게 드래그 앤 드롭 기능을 구현할 수 있습니다. Beautiful Dnd의 다른 기능과 옵션에 대해서는 공식 문서를 참조하시기 바랍니다. Happy coding!