[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 단계별 진행 상황 표시하기

이번에는 React 컴포넌트에서 Beautiful Dnd 라이브러리를 사용하여 드래그 앤 드롭으로 단계별 진행 상황을 표시하는 방법에 대해 알아보겠습니다.

Beautiful Dnd란?

Beautiful Dnd는 React용 드래그 앤 드롭 라이브러리로, 사용자가 컴포넌트를 드래그하여 재정렬하거나 다른 컨테이너로 이동할 수 있게 해줍니다. 사용자 친화적인 드래그 앤 드롭 경험을 제공하며, 쉽게 사용할 수 있는 API를 제공합니다.

설치 및 설정

먼저, 프로젝트에 Beautiful Dnd를 설치해야 합니다. npm을 사용하여 다음 명령어를 실행합니다.

npm install react-beautiful-dnd

그리고 해당 컴포넌트에서 Beautiful Dnd를 import 합니다.

import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';

컴포넌트 설정

이제 Beautiful Dnd를 사용하여 컴포넌트의 드래그 앤 드롭을 설정할 차례입니다.

먼저, DragDropContext 컴포넌트를 사용하여 드래그 앤 드롭 기능을 감싸줍니다.

<DragDropContext onDragEnd={handleDragEnd}>
  {/* 드래그 앤 드롭으로 설정할 컴포넌트들 */}
</DragDropContext>

handleDragEnd 함수는 드래그 앤 드롭이 완료되었을 때 호출되는 콜백 함수입니다.

다음으로, 드래그 앤 드롭을 적용할 컴포넌트를 Droppable과 Draggable로 감싸줍니다. Droppable은 드래그 앤 드롭이 가능한 컨테이너를 나타내고, Draggable은 실제로 드래그 가능한 항목을 나타냅니다.


<DragDropContext onDragEnd={handleDragEnd}>
  <Droppable droppableId="droppable">
    {(provided, snapshot) => (
      <div
        {...provided.droppableProps}
        ref={provided.innerRef}
        style={{
          background: snapshot.isDraggingOver ? 'lightblue' : 'lightgrey',
          padding: 16,
          width: 250,
          minHeight: 200,
        }}
      >
        {items.map((item, index) => (
          <Draggable key={item.id} draggableId={item.id} index={index}>
            {(provided, snapshot) => (
              <div
                ref={provided.innerRef}
                {...provided.draggableProps}
                {...provided.dragHandleProps}
                style={{
                  userSelect: 'none',
                  padding: 16,
                  margin: '0 0 8px 0',
                  minHeight: '50px',
                  backgroundColor: snapshot.isDragging ? '#263B4A' : '#456C86',
                  color: 'white',
                  ...provided.draggableProps.style,
                }}
              >
                {item.content}
              </div>
            )}
          </Draggable>
        ))}
        {provided.placeholder}
      </div>
    )}
  </Droppable>
</DragDropContext>

위의 예시에서, items는 드래그 앤 드롭할 항목들의 배열입니다. 이 배열을 통해 각 항목을 Draggable으로 렌더링합니다.

드래그 앤 드롭 완료 처리

드래그 앤 드롭이 완료되었을 때 호출되는 handleDragEnd 함수를 정의해야 합니다.

const handleDragEnd = (result) => {
  if (!result.destination) {
    return;
  }

  const itemsCopy = Array.from(items);
  const [reorderedItem] = itemsCopy.splice(result.source.index, 1);
  itemsCopy.splice(result.destination.index, 0, reorderedItem);

  setItems(itemsCopy);
};

위의 예시에서, items 배열에서 드래그된 항목을 재정렬하여 업데이트합니다.

결론

Beautiful Dnd를 사용하여 React 컴포넌트에서 드래그 앤 드롭으로 단계별 진행 상황을 표시하는 방법에 대해 알아보았습니다. Beautiful Dnd는 사용자 친화적인 드래그 앤 드롭 경험을 제공하며, 쉽게 사용할 수 있는 API를 제공합니다.

더 많은 자세한 정보는 Beautiful Dnd 공식 문서를 참고하십시오.