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

드래그 앤 드롭은 웹 애플리케이션에서 사용자가 요소를 드래그하여 다른 위치로 이동시키는 기능입니다. 이 기능은 사용자 경험을 향상시키고 사용자들에게 직관적인 인터페이스를 제공하는 가장 흔한 방법 중 하나입니다. 이번 기술 블로그에서는 React 라이브러리에서 제공하는 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소를 선택하는 방법에 대해 알아보겠습니다.

Beautiful Dnd란?

Beautiful Dnd는 드래그 앤 드롭 기능을 구현하기 위한 React 라이브러리입니다. 이 라이브러리는 React 애플리케이션의 컴포넌트 간에 요소를 드래그 앤 드롭으로 이동시키는 기능을 제공합니다. Beautiful Dnd는 사용하기 쉬우며, 많은 커스터마이징 옵션을 제공하여 다양한 UI 요구에 맞게 사용할 수 있습니다.

설치

Beautiful Dnd를 사용하기 위해 우선 해당 라이브러리를 설치해야 합니다. npm을 사용하는 경우 다음 명령을 실행하여 설치할 수 있습니다.

npm install react-beautiful-dnd

사용 방법

Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소를 선택하려면 다음과 같은 단계를 따라야 합니다.

  1. Beautiful Dnd의 DragDropContext 컴포넌트를 사용하여 드래그 앤 드롭을 구현할 컨테이너를 생성합니다.
import { DragDropContext } from 'react-beautiful-dnd';

function App() {
  return (
    <DragDropContext>
      {/* 드래그 앤 드롭 기능이 필요한 컴포넌트들을 포함시킵니다. */}
    </DragDropContext>
  );
}
  1. 드래그 앤 드롭을 구현할 요소들을 Beautiful Dnd의 Draggable 컴포넌트로 감싸줍니다.
import { Draggable } from 'react-beautiful-dnd';

function Item({ item, index }) {
  return (
    <Draggable draggableId={`item-${item.id}`} index={index}>
      {(provided) => (
        <div
          ref={provided.innerRef}
          {...provided.draggableProps}
          {...provided.dragHandleProps}
        >
          {/* 요소의 내용을 표시합니다. */}
          {item.content}
        </div>
      )}
    </Draggable>
  );
}
  1. 드래그 앤 드롭 기능을 적용할 컨테이너 컴포넌트에서 Beautiful Dnd의 Droppable 컴포넌트로 감싸줍니다.
import { Droppable } from 'react-beautiful-dnd';

function Container({ items }) {
  return (
    <Droppable droppableId="container">
      {(provided) => (
        <div ref={provided.innerRef} {...provided.droppableProps}>
          {/* 드래그 앤 드롭 기능이 적용될 요소들을 포함시킵니다. */}
          {items.map((item, index) => (
            <Item key={item.id} item={item} index={index} />
          ))}
          {provided.placeholder}
        </div>
      )}
    </Droppable>
  );
}
  1. 컨테이너 컴포넌트에서 해당 요소들을 업데이트하고, Beautiful Dnd의 onDragEnd 콜백 함수를 구현하여 드래그 앤 드롭 결과를 처리합니다.
function App() {
  const [items, setItems] = useState([...]);

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

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

    setItems(newList);
  };

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <Container items={items} />
    </DragDropContext>
  );
}

위의 단계를 따라서 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소를 선택할 수 있습니다. 이를 통해 사용자들은 직관적이고 쉽게 요소를 이동시킬 수 있게 됩니다.

마치며

Beautiful Dnd는 React에서 드래그 앤 드롭 기능을 구현하기 위한 강력한 도구입니다. 이 라이브러리를 사용하여 사용자 경험을 향상시키고 직관적인 인터페이스를 제공하는 웹 애플리케이션을 만들어보세요. Beautiful Dnd에 대한 자세한 내용은 공식 문서를 참조하시기 바랍니다.

참고 자료: