React에서 드래그 앤 드롭(Drag and Drop)을 구현하는 방법은 여러 가지가 있지만, 실무에서는 대부분 react-beautiful-dnd 또는 dnd-kit 같은 라이브러리를 사용합니다. 직접 이벤트를 다루는 것보다 훨씬 생산적이고 안정적입니다.
1. react-beautiful-dnd 설치와 기본 구조
먼저 라이브러리를 설치하세요.
npm install react-beautiful-dnd
기본 드래그 앤 드롭 인터페이스는 DragDropContext, Droppable, Draggable 세 가지 컴포넌트로 구성됩니다.
2. 간단한 Todo 리스트 예제
import React, { useState } from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
const initialItems = [
{ id: '1', content: '아이템 1' },
{ id: '2', content: '아이템 2' },
{ id: '3', content: '아이템 3' },
];
function App() {
const [items, setItems] = useState(initialItems);
const onDragEnd = (result) => {
if (!result.destination) return;
const newItems = Array.from(items);
const [moved] = newItems.splice(result.source.index, 1);
newItems.splice(result.destination.index, 0, moved);
setItems(newItems);
};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="droppable">
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
{items.map((item, index) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
style={{
userSelect: 'none',
padding: 16,
margin: '0 0 8px 0',
backgroundColor: '#eee',
...provided.draggableProps.style
}}
>
{item.content}
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
);
}
export default App;
이 코드는 아이템 리스트를 드래그해서 순서를 바꿀 수 있게 해줍니다. 핵심은 onDragEnd에서 상태를 업데이트하는 부분입니다.
3. 팁과 주의사항
- 드래그 가능 아이템과 드롭 가능한 영역을 명확하게 분리해야 합니다.
- 스타일링 시 드래그 중인 아이템에 대한 시각적 피드백을 주는 것이 UX를 좋게 만듭니다.
- 복잡한 다중 리스트 드래그가 필요하면
react-beautiful-dnd문서를 참조하세요.
직접 이벤트를 제어하는 방법도 있지만, 유지보수성과 호환성 측면에서 검증된 라이브러리를 쓰는 것이 생산적입니다.
'React' 카테고리의 다른 글
| React에서 접근성을 고려한 UI 컴포넌트 설계 (0) | 2026.04.23 |
|---|---|
| React Native와 웹 React 코드 재사용 전략 (1) | 2026.04.23 |
| React에서 파일 업로드 기능 구현하기 (0) | 2026.04.22 |
| React와 GraphQL Apollo Client 연동하기 (1) | 2026.04.22 |
| React에서 환경 변수 관리하기 (0) | 2026.04.22 |