[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 이미지 갤러리 만들기

이번 포스트에서는 Beautiful Dnd 라이브러리를 이용하여 드래그 앤 드롭으로 이미지 갤러리를 만드는 방법에 대해 알아보겠습니다. Beautiful Dnd는 React용 드래그 앤 드롭 라이브러리로, 사용자 친화적인 인터페이스를 제공하며, 간단하게 커스터마이즈할 수 있는 기능을 제공합니다.

Beautiful Dnd란?

Beautiful Dnd는 React 컴포넌트를 사용하여 드래그 앤 드롭 기능을 구현할 수 있는 라이브러리입니다. 이 라이브러리는 다른 요소들과의 상호작용성을 간편하게 관리하고, 재사용 가능한 드래그 앤 드롭 컴포넌트를 제공합니다. Beautiful Dnd는 가볍고 빠른 성능을 위해 최적화되어 있으며, 실시간 애플리케이션의 요구 사항을 충족시키는 데 도움이 됩니다.

Beautiful Dnd 설치하기

Beautiful Dnd를 사용하기 위해 먼저 프로젝트에 패키지를 설치해야 합니다. npm을 사용하는 경우, 아래의 명령어를 실행하여 패키지를 설치할 수 있습니다.

npm install react-beautiful-dnd

Yarn을 사용하는 경우에는 다음 명령어를 실행합니다.

yarn add react-beautiful-dnd

이미지 갤러리 컴포넌트 만들기

이제 Beautiful Dnd를 사용하여 이미지 갤러리 컴포넌트를 만들어보겠습니다. 먼저, 필요한 컴포넌트와 스타일 파일을 import합니다.

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

이미지 갤러리 컴포넌트를 만들기 위해 함수 컴포넌트를 사용하고, 초기 이미지들을 useState를 통해 관리합니다.

const ImageGallery = () => {
  const [images, setImages] = useState([
    { id: 'image1', src: 'image1.jpg' },
    { id: 'image2', src: 'image2.jpg' },
    { id: 'image3', src: 'image3.jpg' },
    //...
  ]);

  // 드래그 앤 드롭 이벤트가 발생했을 때 실행되는 함수
  const handleDragEnd = (result) => {
    if (!result.destination) return;

    const newImages = Array.from(images);
    const [reorderedImage] = newImages.splice(result.source.index, 1);
    newImages.splice(result.destination.index, 0, reorderedImage);
    
    setImages(newImages);
  };
};

<DragDropContext> 컴포넌트로 드래그 앤 드롭 기능을 래핑하고, <Droppable> 컴포넌트로 드롭 가능한 영역을 만듭니다.

return (
  <div className="image-gallery">
    <DragDropContext onDragEnd={handleDragEnd}>
      <Droppable droppableId="images">
        {(provided) => (
          <div
            {...provided.droppableProps}
            ref={provided.innerRef}
            className="gallery-container"
          >
            {images.map((image, index) => (
              <Draggable key={image.id} draggableId={image.id} index={index}>
                {(provided, snapshot) => (
                  <img
                    ref={provided.innerRef}
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                    src={image.src}
                    alt={image.id}
                    className={`gallery-image ${
                      snapshot.isDragging ? 'dragging' : ''
                    }`}
                  />
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  </div>
);

위의 코드에서는 images 배열을 map 함수를 사용하여 이미지 요소들을 렌더링하고, <Draggable> 컴포넌트를 이용해 각 이미지를 드래그할 수 있도록 만듭니다. 이때 snapshot.isDragging을 통해 해당 이미지가 드래그 중인지 확인할 수 있습니다.

CSS 스타일링 추가하기

지금까지 만든 이미지 갤러리를 스타일링하기 위해 ImageGallery.css 파일에 아래의 스타일을 추가해주세요.

.image-gallery {
  display: flex;
  justify-content: center;
}

.gallery-container {
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
}

.gallery-image {
  width: 200px;
  height: 200px;
  margin: 10px;
  border-radius: 5px;
  object-fit: cover;
}

.dragging {
  opacity: 0.5;
}

마무리

Beautiful Dnd 라이브러리를 사용하면 쉽게 드래그 앤 드롭 기능을 구현할 수 있습니다. 이번 예제에서는 이미지 갤러리를 만들었지만, 실제 프로젝트에서는 다양한 요소들을 드래그 앤 드롭으로 구성할 수 있습니다. Beautiful Dnd 문서에서 더 자세한 정보와 예제를 찾아볼 수 있으니 필요한 경우 참조해보세요.