[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소 배경 이미지 변경하기

이번 블로그 포스트에서는 Beautiful Dnd 라이브러리를 사용하여 JavaScript로 드래그 앤 드롭 기능을 구현하고, 요소의 배경 이미지를 변경하는 방법에 대해 알아보겠습니다.

Beautiful Dnd란?

Beautiful Dnd는 React를 기반으로한 드래그 앤 드롭 라이브러리로, 웹 애플리케이션에서 요소를 드래그하여 다른 위치로 이동하거나 재정렬하는 기능을 쉽게 구현할 수 있습니다.

사용 방법

먼저, Beautiful Dnd를 설치하기 위해 npm을 사용하여 패키지를 설치합니다.

npm install react-beautiful-dnd

그리고 해당 모듈을 import 합니다.

import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";

Beautiful Dnd의 주요 컴포넌트는 DragDropContext, Droppable, Draggable 입니다. DragDropContext는 드래그 앤 드롭 이벤트를 처리하는 컨테이너 역할을 하며, Droppable은 드래그할 수 있는 요소를 감싸주는 역할을 하고, Draggable은 실제로 드래그할 수 있는 요소를 나타냅니다.

<DragDropContext>
  <Droppable>
    {provided => (
      <div ref={provided.innerRef} {...provided.droppableProps}>
        {items.map((item, index) => (
          <Draggable>
            {provided => (
              <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
                {item.content}
              </div>
            )}
          </Draggable>
        ))}
        {provided.placeholder}
      </div>
    )}
  </Droppable>
</DragDropContext>

위의 예제 코드에서는 DragDropContext, Droppable, Draggable 컴포넌트를 중첩하여 드래그 앤 드롭을 구현하고 있습니다. DraggableDraggablePropsDragHandleProps를 제공하는데, 해당 프로퍼티를 요소에 추가하여 드래그 앤 드롭 이벤트를 바인딩할 수 있습니다.

배경 이미지 변경하기

이제 요소의 배경 이미지를 변경하는 방법에 대해 알아보겠습니다. Beautiful Dnd에서는 요소의 상태를 관리하기 위해 state를 사용합니다. 따라서, 요소의 배경 이미지를 변경하려면 해당 요소의 상태를 업데이트해야 합니다.


state = {
  items: [
    { id: "1", content: "Item 1", image: "image1.jpg" },
    { id: "2", content: "Item 2", image: "image2.jpg" },
    // ...
  ]
};

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

  const items = Array.from(this.state.items);
  const [reorderedItem] = items.splice(result.source.index, 1);
  items.splice(result.destination.index, 0, reorderedItem);

  this.setState({ items });
};

render() {
  return (
    <DragDropContext onDragEnd={this.onDragEnd}>
      <Droppable droppableId="droppable">
        {provided => (
          <div ref={provided.innerRef} {...provided.droppableProps}>
            {this.state.items.map((item, index) => (
              <Draggable key={item.id} draggableId={item.id} index={index}>
                {provided => (
                  <div
                    ref={provided.innerRef}
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                    style={{ backgroundImage: `url(${item.image})` }}
                  >
                    {item.content}
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  );
}

위의 코드에서는 items 배열 안에 image 프로퍼티를 추가하여 각 요소의 배경 이미지를 정의합니다. onDragEnd 메서드를 통해 드래그 앤 드롭 이벤트가 발생했을 때, 해당 메서드에서 배열의 순서를 업데이트하고, setState를 통해 상태를 업데이트합니다. 마지막으로, style 속성을 사용하여 배경 이미지를 적용합니다.

드래그 앤 드롭으로 요소의 순서를 변경하면 배경 이미지도 함께 변경됩니다.

마치며

이번 포스트에서는 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소의 배경 이미지를 변경하는 방법에 대해 알아보았습니다. Beautiful Dnd를 사용하면 웹 애플리케이션에서 손쉽게 드래그 앤 드롭 기능을 구현할 수 있습니다. 자세한 사항은 Beautiful Dnd의 공식 문서를 참고하시기 바랍니다.

Happy coding!