[javascript] Beautiful Dnd를 사용하여 리스트 항목 드래그 앤 드롭 구현하기

이번 포스트에서는 Beautiful Dnd라이브러리를 사용하여 웹앱에서 리스트 항목을 드래그 앤 드롭으로 이동시키는 방법을 알아보겠습니다.

Beautiful Dnd란?

Beautiful Dnd는 React용 드래그 앤 드롭 라이브러리로, 사용자 경험을 향상시키기 위해 쉽게 구현할 수 있도록 도와줍니다. 리스트나 테이블과 같은 요소들을 드래그하여 자유롭게 이동시킬 수 있습니다.

설치

먼저 Beautiful Dnd를 사용하기 위해 패키지를 설치해야 합니다. 아래의 명령어를 사용하여 설치할 수 있습니다.

npm install react-beautiful-dnd

사용 방법

Beautiful Dnd를 사용하여 리스트 항목 드래그 앤 드롭을 구현하는 방법을 살펴보겠습니다.

  1. Beautiful Dnd를 import합니다.
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
  1. 드래그 앤 드롭을 적용할 컨테이너를 설정합니다.
<DragDropContext onDragEnd={handleDragEnd}>
  <Droppable droppableId="list">
    {(provided) => (
      <div ref={provided.innerRef} {...provided.droppableProps}>
        {/* 리스트 항목들 */}
      </div>
    )}
  </Droppable>
</DragDropContext>
  1. 각 리스트 항목을 Draggable으로 감싸줍니다.
{items.map((item, index) => (
  <Draggable key={item.id} draggableId={item.id} index={index}>
    {(provided) => (
      <div
        ref={provided.innerRef}
        {...provided.draggableProps}
        {...provided.dragHandleProps}
      >
        {/* 리스트 항목 내용 */}
      </div>
    )}
  </Draggable>
))}
  1. 항목을 이동시키는 로직을 구현합니다.
const handleDragEnd = (result) => {
  if (!result.destination) {
    return;
  }

  const items = Array.from(items); // 항목 배열 복사
  const [removed] = items.splice(result.source.index, 1); // 이동된 항목 제거
  items.splice(result.destination.index, 0, removed); // 이동된 항목 삽입

  setItems(items); // 새로운 항목 배열로 업데이트
};

예제

다음은 Beautiful Dnd를 사용하여 리스트 항목 드래그 앤 드롭을 구현한 예제입니다.


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

const App = () => {
  const [items, setItems] = useState([
    { id: '1', content: '항목 1' },
    { id: '2', content: '항목 2' },
    { id: '3', content: '항목 3' },
  ]);

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

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

    setItems(newItems);
  };

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <Droppable droppableId="list">
        {(provided) => (
          <div ref={provided.innerRef} {...provided.droppableProps}>
            {items.map((item, index) => (
              <Draggable key={item.id} draggableId={item.id} index={index}>
                {(provided) => (
                  <div
                    ref={provided.innerRef}
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                    style={{
                      padding: '8px',
                      margin: '8px',
                      backgroundColor: '#ddd',
                    }}
                  >
                    {item.content}
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  );
};

export default App;

위 예제를 사용하여 웹앱에서 리스트 항목을 드래그 앤 드롭으로 이동시킬 수 있습니다.

결론

이번 포스트에서는 Beautiful Dnd를 사용하여 리스트 항목 드래그 앤 드롭을 구현하는 방법을 알아보았습니다. Beautiful Dnd는 React 개발자에게 유용한 도구로, 사용자 경험을 향상시키는 데 큰 도움이 될 수 있습니다.

더 자세한 내용은 Beautiful Dnd 공식 문서를 참고하십시오.