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

드래그 앤 드롭(Drag and Drop) 기능은 사용자가 요소를 마우스로 잡고 원하는 위치로 이동시킬 수 있는 인터랙션 기능입니다. 이 기능을 활용하여 Beautiful Dnd 패키지를 사용하여 드래그 앤 드롭으로 계산기를 만들어보겠습니다.

개요

우리가 만들 계산기는 간단한 더하기와 빼기연산을 수행할 수 있는 계산기입니다. 사용자는 숫자를 드래그하고 드롭 영역으로 이동시켜서 연산을 수행할 수 있습니다.

설치

Beautiful Dnd 패키지를 설치하기 위해서는 npm을 사용합니다. 프로젝트 디렉토리에서 다음의 명령어를 실행해주세요.

npm install beautiful-dnd

구현

첫번째로, Beautiful Dnd 패키지를 import 합니다.

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

다음으로, 스테이트를 생성합니다. items에는 사용자가 드래그하는 숫자가 저장됩니다.

const [items, setItems] = React.useState([1, 2, 3, 4, 5]);

이제, Beautiful Dnd를 적용할 컴포넌트를 만들겠습니다. 드래그 가능한 숫자를 렌더링하고, 드롭 영역을 만들어 연산 결과를 표시합니다.

const Calculator = () => {
  return (
    <div>
      <DragDropContext>
        <Droppable droppableId="numbers">
          {(provided) => (
            <div ref={provided.innerRef} {...provided.droppableProps}>
              {items.map((item, index) => (
                <Draggable key={item} draggableId={item.toString()} index={index}>
                  {(provided) => (
                    <div
                      ref={provided.innerRef}
                      {...provided.draggableProps}
                      {...provided.dragHandleProps}
                    >
                      {item}
                    </div>
                  )}
                </Draggable>
              ))}
              {provided.placeholder}
            </div>
          )}
        </Droppable>
        <div>
          {/* 드롭 영역 */}
        </div>
      </DragDropContext>
    </div>
  );
};

마지막으로, App 컴포넌트에서 Calculator 컴포넌트를 렌더링합니다.

const App = () => {
  return (
    <div>
      <h1>드래그  드롭 계산기</h1>
      <Calculator />
    </div>
  );
};

export default App;

이제 더하기와 빼기 연산을 수행할 수 있는 드롭 영역을 구현해야 합니다. Droppable 컴포넌트의 onDragEnd 콜백 함수를 사용하여 숫자를 이동시키는 로직을 구현할 수 있습니다.

const Calculator = () => {
  const onDragEnd = (result) => {
    const { source, destination } = result;

    if (!destination) {
      return;
    }

    const newItems = [...items];
    const [removed] = newItems.splice(source.index, 1);
    newItems.splice(destination.index, 0, removed);

    setItems(newItems);
  };

  return (
    <div>
      <DragDropContext onDragEnd={onDragEnd}>
        {/* 이하 동일 */}

이제 사용자가 드롭 영역으로 숫자를 이동시킬 때마다 onDragEnd 함수가 호출되고, 숫자의 순서가 변경됩니다.

결론

Beautiful Dnd 패키지를 사용하여 드래그 앤 드롭으로 계산기를 만들었습니다. 사용자는 숫자를 드래그하고 드롭 영역으로 이동시켜서 더하기와 빼기 연산을 수행할 수 있습니다.

더 많은 기능, 예외 처리 및 스타일링을 추가할 수 있으며, Beautiful Dnd의 문서를 참조하여 더욱 많은 기능을 사용할 수 있습니다.

참고