[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 배치표 만들기

이번 포스트에서는 Beautiful Dnd 라이브러리를 사용하여 드래그 앤 드롭으로 배치표를 만드는 방법을 알아보겠습니다. Beautiful Dnd는 React 기반의 드래그 앤 드롭 라이브러리로, 사용자 친화적인 드래그 앤 드롭 인터페이스를 쉽게 구현할 수 있도록 도와줍니다.

Beautiful Dnd 설치

먼저 Beautiful Dnd를 설치해야 합니다. npm을 사용하여 다음 명령어를 실행하면 됩니다:

npm install react-beautiful-dnd

또는 yarn을 사용하시는 경우 다음 명령어를 실행하세요:

yarn add react-beautiful-dnd

컴포넌트 구조

먼저, Beautiful Dnd를 사용하기 위해 필요한 컴포넌트 구조를 준비해야 합니다. 일반적으로는 다음과 같은 구조를 사용합니다:

<DragDropContext>
  <Droppable>
    <Draggable>
      {/* 드래그 앤 드롭 기능이 적용될 컴포넌트 */}
    </Draggable>
  </Droppable>
</DragDropContext>

예제 코드

간단한 예제로, 3개의 항목을 드래그 앤 드롭으로 재배치하는 배치표를 만들어보겠습니다.

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

const items = ['항목 1', '항목 2', '항목 3'];

const App = () => {
  const onDragEnd = (result) => {
    // 드롭 완료 후의 동작을 정의합니다.
    // 여기서는 items의 순서를 변경하는 로직을 작성합니다.
    const { destination, source } = result;
    if (!destination) {
      return;
    }
    const newItems = Array.from(items);
    const [removed] = newItems.splice(source.index, 1);
    newItems.splice(destination.index, 0, removed);
    // 변경된 items를 상태로 업데이트합니다.
    setItems(newItems);
  };

  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <Droppable droppableId="items">
        {(provided) => (
          <div {...provided.droppableProps} ref={provided.innerRef}>
            {items.map((item, index) => (
              <Draggable key={item} draggableId={item} index={index}>
                {(provided) => (
                  <div
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                    ref={provided.innerRef}
                  >
                    {item}
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  );
};

export default App;

위의 예제 코드에서 onDragEnd 함수는 드롭 완료 후의 동작을 정의합니다. 여기서는 items 배열의 순서를 변경하는 로직을 작성하였습니다.

실행결과

드래그앤드롭 예제

실행 결과로는 3개의 항목을 드래그해서 재배치할 수 있는 인터페이스가 나타납니다. 항목을 드래그하면 드롭 가능한 영역에 그림자 효과와 함께 이동합니다.

결론

이번 포스트에서는 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 배치표를 만드는 방법에 대해 알아보았습니다. Beautiful Dnd를 사용하면 사용자 친화적인 드래그 앤 드롭 인터페이스를 쉽게 구현할 수 있습니다.

더 자세한 내용은 Beautiful Dnd 공식 문서를 참고하시기 바랍니다.

Happy coding!