Beautiful Dnd는 React용 드래그 앤 드롭 라이브러리로, 사용하기 쉬운 인터페이스와 유연한 기능을 제공합니다. 이번 블로그 포스트에서는 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 테이블을 만드는 방법에 대해 알아보겠습니다.
1. Beautiful Dnd 설치하기
먼저 Beautiful Dnd를 설치해야 합니다. 다음 명령어를 사용하여 패키지를 설치합니다:
npm install react-beautiful-dnd
2. 테이블 데이터 설정하기
드래그 앤 드롭으로 편집할 테이블의 데이터를 설정해야 합니다. 예를 들어, 다음과 같은 데이터를 가진 items
배열을 선언합니다:
const items = [
{ id: '1', text: '항목 1' },
{ id: '2', text: '항목 2' },
{ id: '3', text: '항목 3' },
// ...
];
3. 드래그 앤 드롭 컴포넌트 생성하기
Beautiful Dnd를 사용하여 드래그 앤 드롭 기능을 적용할 컴포넌트를 생성합니다. 각 항목을 나타내는 Item
컴포넌트를 만들어야합니다.
Item
컴포넌트는 react-beautiful-dnd
에서 제공하는 Draggable
컴포넌트를 감싸고 있어야합니다. Draggable
컴포넌트는 드래그 가능한 항목을 만들어주는 역할을 합니다.
import { Draggable } from 'react-beautiful-dnd';
const Item = ({ item, index }) => {
return (
<Draggable draggableId={item.id} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{item.text}
</div>
)}
</Draggable>
);
};
4. 드롭 영역 컴포넌트 생성하기
Droppable
컴포넌트를 사용하여 드롭 영역을 만들어야 합니다. Droppable
컴포넌트는 아이템을 드롭할 수 있는 영역을 생성해줍니다.
import { Droppable } from 'react-beautiful-dnd';
const DropZone = ({ items }) => {
return (
<Droppable droppableId="table">
{(provided) => (
<div
ref={provided.innerRef}
{...provided.droppableProps}
>
{items.map((item, index) => (
<Item key={item.id} item={item} index={index} />
))}
{provided.placeholder}
</div>
)}
</Droppable>
);
};
5. 드래그 앤 드롭 업데이트 처리하기
드래그 앤 드롭으로 항목을 이동하였을 때, 변경된 순서를 업데이트해주어야합니다. 이를 위해 Beautiful Dnd에서 제공하는 onDragEnd
이벤트를 사용합니다.
const onDragEnd = (result) => {
if (!result.destination) {
return;
}
const rearrangedItems = Array.from(items);
const [removed] = rearrangedItems.splice(result.source.index, 1);
rearrangedItems.splice(result.destination.index, 0, removed);
// 변경된 순서로 업데이트
// ...
};
6. 전체 컴포넌트 구성하기
위에서 생성한 DropZone
컴포넌트와 onDragEnd
이벤트를 전체 컴포넌트에 적용합니다.
import { DragDropContext } from 'react-beautiful-dnd';
const App = () => {
return (
<DragDropContext onDragEnd={onDragEnd}>
<DropZone items={items} />
</DragDropContext>
);
};
마무리
이제 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 테이블을 만들 수 있습니다. 이러한 기능은 사용자가 쉽게 테이블을 편집할 수 있도록 도와줍니다.
더 자세한 내용은 Beautiful Dnd 공식 문서를 참조해주세요.