본문 바로가기

React

React로 드래그 앤 드롭 인터페이스 만들기

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 문서를 참조하세요.

직접 이벤트를 제어하는 방법도 있지만, 유지보수성과 호환성 측면에서 검증된 라이브러리를 쓰는 것이 생산적입니다.