[javascript] Beautiful Dnd의 동작 원리

Beautiful Dnd는 React를 사용하는 웹 개발자들 사이에서 널리 사용되는 라이브러리입니다. 이 라이브러리는 Drag and Drop(DND) 기능을 구현하는 데 도움을 줍니다. Beautiful Dnd의 주요 동작 원리에 대해 알아보겠습니다.

1. 드래그 앤 드롭 컴포넌트

Beautiful Dnd에서는 드래그 앤 드롭을 구현하기 위해 DragDropContext 컴포넌트를 사용합니다. 이 컴포넌트는 드래그 앤 드롭 기능을 적용할 영역을 지정하는 역할을 합니다.

import { DragDropContext } from 'react-beautiful-dnd';

const App = () => {
  return (
    <DragDropContext>
      {/* 드래그 앤 드롭 기능을 적용할 컴포넌트들 */}
    </DragDropContext>
  );
};

export default App;

2. 드래그 가능한 항목

드래그 앤 드롭 기능을 적용할 컴포넌트 중 드래그 가능한 항목은 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}
        >
          {/* 드래그 가능한 항목 내용 */}
        </div>
      )}
    </Draggable>
  );
};

3. 드롭 영역

드래그 앤 드롭 기능을 적용할 컴포넌트 중 드롭 영역은 Droppable 컴포넌트로 감싸야 합니다. 이 컴포넌트는 드롭 영역에 대한 속성과 동작을 정의하는 역할을 합니다.

import { Droppable } from 'react-beautiful-dnd';

const Container = ({ items }) => {
  return (
    <Droppable droppableId="items">
      {(provided) => (
        <div ref={provided.innerRef} {...provided.droppableProps}>
          {/* 드롭 영역에 표시할 컴포넌트들 */}
          {items.map((item, index) => (
            <Item key={item.id} item={item} index={index} />
          ))}
          {provided.placeholder}
        </div>
      )}
    </Droppable>
  );
};

4. 드래그 앤 드롭 이벤트 처리

Beautiful Dnd는 onDragStart, onDragUpdate, onDragEnd 등의 이벤트 콜백 함수를 제공하여 드래그 앤 드롭 이벤트를 처리할 수 있습니다. 이러한 콜백 함수를 활용하여 드래그 앤 드롭 동작에 대한 로직을 작성할 수 있습니다.

const onDragEnd = (result) => {
  const { destination, source, draggableId } = result;

  if (!destination) {
    // 드롭 영역 밖으로 드래그되었을 때 처리할 내용
    return;
  }

  if (
    destination.droppableId === source.droppableId &&
    destination.index === source.index
  ) {
    // 같은 영역에서 같은 위치로 드래그되었을 때 처리할 내용
    return;
  }

  // 드롭된 항목에 대한 로직 처리
};

// ...

<DragDropContext onDragEnd={onDragEnd}>
  {/* 드래그 앤 드롭 기능을 적용할 컴포넌트들 */}
</DragDropContext>

Beautiful Dnd를 통해 간단하게 드래그 앤 드롭 기능을 구현할 수 있습니다. 필요에 따라 세부적인 동작 원리와 API 문서를 참고하여 더 복잡한 드래그 앤 드롭 기능을 구현할 수도 있습니다.

참고 자료