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

Beautiful Dnd는 React를 위한 드래그 앤 드롭 라이브러리입니다. 이 라이브러리를 사용하면 사용자가 UI 요소를 드래그하여 다른 위치로 이동하거나 삭제할 수 있습니다. 이번 포스트에서는 Beautiful Dnd를 사용하여 요소를 드래그 앤 드롭으로 삭제하는 방법에 대해 알아보겠습니다.

1. Beautiful Dnd 설치

먼저 Beautiful Dnd를 설치해야 합니다. 프로젝트 디렉토리에서 다음 명령어를 실행하여 Beautiful Dnd를 설치합니다.

npm install react-beautiful-dnd

2. Beautiful Dnd 사용하기

Beautiful Dnd를 사용하기 위해 필요한 두 가지 요소가 있습니다. 첫 번째는 드래그 앤 드롭 컨테이너이고, 두 번째는 드래그 가능한 요소들입니다.


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

const App = () => {
  const [items, setItems] = useState(['아이템 1', '아이템 2', '아이템 3']);

  const handleDragEnd = (result) => {
    // 드래그가 끝났을 때 호출됩니다.
    if (!result.destination) return; // 유효한 드롭 대상이 없으면 종료합니다.

    const updatedItems = [...items];
    updatedItems.splice(result.source.index, 1); // 드래그된 아이템을 삭제합니다.
    setItems(updatedItems);
  };

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <Droppable droppableId="droppable">
        {(provided, snapshot) => (
          <div
            ref={provided.innerRef}
            {...provided.droppableProps}
            style={{ background: snapshot.isDraggingOver ? 'lightblue' : 'white' }}
          >
            {items.map((item, index) => (
              <Draggable key={item} draggableId={item} index={index}>
                {(provided, snapshot) => (
                  <div
                    ref={provided.innerRef}
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                    style={{
                      userSelect: 'none',
                      padding: 16,
                      margin: '0 0 8px 0',
                      background: snapshot.isDragging ? 'lightgreen' : 'white',
                      ...provided.draggableProps.style
                    }}
                  >
                    {item}
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  );
};

export default App;

위의 코드를 살펴보면, App 컴포넌트에서 items라는 상태를 관리하고 있습니다. items 배열에는 드롭 가능한 아이템들이 포함되어 있습니다. handleDragEnd 함수에서는 드래그가 끝났을 때 호출되어, 선택된 아이템을 items 배열에서 제거합니다.

마무리

이제 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소를 삭제하는 방법을 알아보았습니다. Beautiful Dnd는 다양한 드래그 앤 드롭 상황에서 사용할 수 있는 풍부한 기능을 제공합니다. 자세한 내용은 Beautiful Dnd 공식 문서를 참고하시기 바랍니다.