[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소 복제하기

이전에는 웹 페이지에서 요소를 드래그 앤 드롭으로 복제하는 것은 꽤 번거로운 작업이었습니다. 그러나 react-beautiful-dnd라는 라이브러리를 사용하면 이 작업을 쉽게 수행할 수 있습니다.

Beautiful Dnd란?

react-beautiful-dnd는 React 앱에서 드래그 앤 드롭 기능을 제공하는 라이브러리입니다. 이를 사용하면 사용자 친화적인 인터페이스를 만들 수 있고, 요소의 재정렬, 이동 및 복제 등을 쉽게 구현할 수 있습니다.

설치

먼저, react-beautiful-dnd를 설치해야 합니다. npm을 사용하여 다음 명령을 실행해주세요:

npm install react-beautiful-dnd

요소 복제 구현하기

다음으로, 요소를 드래그 앤 드롭으로 복제하는 예제를 살펴보겠습니다.

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

const initialItems = ['Item 1', 'Item 2', 'Item 3'];

const App = () => {
  const [items, setItems] = useState(initialItems);

  const handleDragEnd = (result) => {
    if (!result.destination) return;
    
    const newItem = items[result.source.index];
    const newItems = [...items];
    
    if (result.destination.index === result.source.index) {
      // 동일한 위치에 놔두었을 때는 아무 작업도 수행하지 않음
      return;
    } else if (result.destination.index > result.source.index) {
      // 현재 위치보다 뒤로 이동한 경우, 인덱스 + 1로 요소를 삽입
      newItems.splice(result.destination.index + 1, 0, newItem);
    } else {
      // 현재 위치보다 앞으로 이동한 경우, 인덱스 그대로 요소를 삽입
      newItems.splice(result.destination.index, 0, newItem);
    }

    setItems(newItems);
  }

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

export default App;

위의 예제에서는 App 컴포넌트 안에 DragDropContext, Droppable, Draggable 컴포넌트를 사용하여 드래그 앤 드롭 기능을 구현합니다.

initialItems 배열에는 초기 상태의 요소들을 선언합니다. useState 훅을 사용하여 items 상태와 setItems 함수를 정의합니다.

handleDragEnd 함수는 드래그 앤 드롭이 끝난 후 호출되며, 요소의 이동에 따라 items 상태를 업데이트합니다. result.destination.index를 사용하여 이동한 위치를 확인하고, newItems 배열을 업데이트합니다.

마지막으로, DragDropContext 컴포넌트로 드래그 앤 드롭을 감싸고, Droppable 컴포넌트로 드롭 가능한 영역을 생성합니다. items.map을 사용하여 각 요소를 Draggable 컴포넌트로 변환합니다.

마무리

이제 react-beautiful-dnd를 사용하여 드래그 앤 드롭으로 요소를 복제하는 방법을 알아보았습니다. 이를 응용하여 사용자 친화적인 인터페이스를 구현할 수 있고, 웹 애플리케이션의 사용성을 개선할 수 있습니다.

더 많은 기능과 사용법은 공식 문서를 참조하시면 도움이 될 것입니다.