[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 퍼즐 만들기

Beautiful Dnd는 React와 함께 사용할 수 있는 강력한 드래그 앤 드롭 라이브러리입니다. 이 라이브러리를 사용하면 웹 애플리케이션에서 아이템을 드래그하여 재정렬하거나 다른 영역으로 이동시킬 수 있습니다.

이번 글에서는 Beautiful Dnd를 사용하여 드래그 앤 드롭 기능을 갖춘 퍼즐을 만드는 방법에 대해 알아보겠습니다.

설치

먼저 Beautiful Dnd를 프로젝트에 설치해야 합니다. 패키지 관리자를 사용하는 경우 다음 명령어를 실행하여 Beautiful Dnd를 설치할 수 있습니다.

npm install react-beautiful-dnd

또는

yarn add react-beautiful-dnd

컴포넌트 구성

퍼즐은 여러 개의 퍼즐 조각으로 구성됩니다. 각각의 조각은 드래그 가능한 아이템으로 표현됩니다. 퍼즐 보드 자체는 Beautiful Dnd의 DragDropContext 컴포넌트로 감싸야 합니다.

아래는 간단한 퍼즐 컴포넌트의 구성 예시입니다.

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

const Puzzle = () => {
  const [puzzlePieces, setPuzzlePieces] = useState([
    { id: '1', content: 'Piece 1' },
    { id: '2', content: 'Piece 2' },
    { id: '3', content: 'Piece 3' },
  ]);

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

    const newPuzzlePieces = [...puzzlePieces];
    const [reorderedPiece] = newPuzzlePieces.splice(result.source.index, 1);
    newPuzzlePieces.splice(result.destination.index, 0, reorderedPiece);

    setPuzzlePieces(newPuzzlePieces);
  };

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <Droppable droppableId="puzzle-pieces">
        {(droppableProvided) => (
          <ul
            className="puzzle-pieces"
            {...droppableProvided.droppableProps}
            ref={droppableProvided.innerRef}
          >
            {puzzlePieces.map((piece, index) => (
              <Draggable key={piece.id} draggableId={piece.id} index={index}>
                {(draggableProvided, draggableSnapshot) => (
                  <li
                    className={`puzzle-piece ${draggableSnapshot.isDragging ? 'dragging' : ''}`}
                    {...draggableProvided.draggableProps}
                    {...draggableProvided.dragHandleProps}
                    ref={draggableProvided.innerRef}
                  >
                    {piece.content}
                  </li>
                )}
              </Draggable>
            ))}
            {droppableProvided.placeholder}
          </ul>
        )}
      </Droppable>
    </DragDropContext>
  );
};

export default Puzzle;

위 코드에서 puzzlePieces 상태 변수는 퍼즐 조각들의 목록을 나타냅니다. handleDragEnd 함수는 드래그 앤 드롭이 끝났을 때 호출되는 콜백 함수로, 퍼즐 조각들의 순서를 업데이트합니다.

결과 확인

위의 퍼즐 컴포넌트를 애플리케이션에 추가하고 렌더링하면 드래그 앤 드롭 기능이 있는 퍼즐을 확인할 수 있습니다.

import React from 'react';
import Puzzle from './Puzzle';

const App = () => {
  return (
    <div className="App">
      <h1>Beautiful Dnd Puzzle</h1>
      <Puzzle />
    </div>
  );
};

export default App;

위 예시는 React 애플리케이션에서 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 퍼즐 만드는 방법을 보여주었습니다. Beautiful Dnd는 다양한 옵션과 기능을 제공하므로, 필요에 따라 자세한 문서를 참조하면 더 다양한 활용이 가능합니다.

참고 자료