[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소 사이 순서 변경하기
Beautiful Dnd는 React를 위한 드래그 앤 드롭 라이브러리로, 요소들의 순서를 쉽게 변경할 수 있도록 도와줍니다. 이 라이브러리는 사용하기 쉽고 많은 커스터마이징 옵션이 있는데, 이번 글에서는 Beautiful Dnd를 사용하여 요소들의 순서를 드래그 앤 드롭으로 변경하는 방법에 대해 알아보겠습니다.
설치
먼저, Beautiful Dnd를 설치해야 합니다. 다음 명령어를 사용하여 npm으로 라이브러리를 설치합니다:
npm install react-beautiful-dnd
사용하기
- Beautiful Dnd를 사용하려는 컴포넌트에서
DragDropContext
를 임포트합니다:
import { DragDropContext } from 'react-beautiful-dnd';
- 요소들의 컨테이너를 만들고, 드래그 앤 드롭으로 순서를 변경하고 싶은 요소들을
Draggable
로 감싸줍니다.Droppable
컴포넌트로 요소들의 컨테이너를 감싸야 합니다:
<DragDropContext>
<Droppable droppableId="droppable">
{(provided, snapshot) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{elements.map((element, index) => (
<Draggable key={element.id} draggableId={element.id} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{element.content}
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
- 순서 변경을 처리하는 핸들러 함수를 작성합니다:
const onDragEnd = (result) => {
if (!result.destination) {
return;
}
const { source, destination } = result;
const updatedElements = Array.from(elements);
const [removed] = updatedElements.splice(source.index, 1);
updatedElements.splice(destination.index, 0, removed);
setElements(updatedElements);
};
DragDropContext
컴포넌트에onDragEnd
핸들러 함수를 전달합니다:
<DragDropContext onDragEnd={onDragEnd}>
{/* ... */}
</DragDropContext>
onDragEnd
핸들러 함수는 드래그 앤 드롭이 완료될 때 호출되며, result
객체를 통해 드래그한 요소와 목적지 정보를 얻을 수 있습니다. 이 정보를 사용하여 순서 변경을 처리하고, 컴포넌트의 상태를 업데이트합니다.
커스터마이징
Beautiful Dnd는 다양한 커스터마이징 옵션을 제공합니다. 예를 들어, 요소를 드래그할 때 발생하는 애니메이션을 변경하거나, 드래그 가능한 영역을 제한하는 등의 설정이 가능합니다. 자세한 내용은 공식 문서를 참조하시기 바랍니다.
이제 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소 사이의 순서를 변경하는 방법을 알아보았습니다. 간단하게 설치하고, 기본적인 사용법과 함께 커스터마이징 옵션을 활용하여 자신만의 드래그 앤 드롭 기능을 구현해보세요!