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

요소를 드래그 앤 드롭으로 필터링하는 기능은 웹 애플리케이션에서 많이 사용되는 기능 중 하나입니다. 이러한 기능을 구현하기 위해 Beautiful Dnd라는 라이브러리를 사용할 수 있습니다. Beautiful Dnd는 React 기반의 드래그 앤 드롭 라이브러리로, 사용자 친화적인 드래그 앤 드롭 기능을 쉽게 구현할 수 있게 해줍니다.

설치

Beautiful Dnd를 사용하기 위해 우선 해당 라이브러리를 설치해야 합니다. npm을 사용한다면 다음 명령어를 실행해주세요:

npm install react-beautiful-dnd

구현

Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소를 필터링하는 예제를 살펴보겠습니다. 이 예제에서는 간단한 목록을 만들고, 사용자가 드래그 앤 드롭으로 요소를 재정렬할 수 있게 합니다.


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

const ItemList = [
  { id: 'item1', text: '아이템 1' },
  { id: 'item2', text: '아이템 2' },
  { id: 'item3', text: '아이템 3' },
];

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

  const handleDragEnd = (result) => {
    if (!result.destination) return; // 드롭 위치가 없으면 종료

    const itemsCopy = [...items];
    const [reorderedItem] = itemsCopy.splice(result.source.index, 1); // 드래그 된 아이템 복사
    itemsCopy.splice(result.destination.index, 0, reorderedItem); // 드랍 위치로 아이템 이동

    setItems(itemsCopy);
  };

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <Droppable droppableId="itemList">
        {(provided) => (
          <ul {...provided.droppableProps} ref={provided.innerRef}>
            {items.map((item, index) => (
              <Draggable key={item.id} draggableId={item.id} index={index}>
                {(provided, snapshot) => (
                  <li
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                    ref={provided.innerRef}
                    style={{
                      backgroundColor: snapshot.isDragging ? 'lightblue' : 'white',
                      ...provided.draggableProps.style,
                    }}
                  >
                    {item.text}
                  </li>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </ul>
        )}
      </Droppable>
    </DragDropContext>
  );
};

export default App;

위의 예제에서는 ItemList 배열에 드래그 앤 드롭할 요소들의 정보가 들어있습니다. App 컴포넌트에서는 items 상태를 사용하여 리스트를 렌더링하고, handleDragEnd 함수를 사용하여 드래그 앤 드롭이 완료되었을 때 상태를 업데이트합니다.

<DragDropContext>, <Droppable>, 그리고 <Draggable> 컴포넌트를 사용하여 드래그 앤 드롭 기능을 구현합니다. 이 컴포넌트들은 Beautiful Dnd 라이브러리에서 제공하는 컴포넌트로, 각각 드래그 앤 드롭 컨텍스트를 생성하고 드롭 가능한 영역과 드래그 가능한 아이템을 만듭니다. 필요한 속성을 전달하여 컴포넌트를 구성하고, 제공된 콜백 함수를 사용하여 원하는 동작을 수행합니다.

결론

Beautiful Dnd를 사용하면 드래그 앤 드롭으로 요소를 필터링하는 기능을 쉽게 구현할 수 있습니다. 해당 라이브러리는 React 기반으로 작성되었으며, 사용자 친화적인 인터페이스와 다양한 커스터마이징 옵션을 제공합니다. 위의 예제를 참고하여 필요한 경우 적절히 수정하여 원하는 동작을 구현해보세요.

참고 자료