[React] react-beautiful-dnd (드래그 앤 드롭 라이브러리)

mangosteen·2024년 3월 21일

react

목록 보기
6/8
  1. npm i react-beautiful-dnd install
    0-1. TS @types 추가 npm i --save-dev @types/react-beautiful-dnd

(npmjs) https://www.npmjs.com/package/react-beautiful-dnd
(github) https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/about/installation.md
(한국어 read.me) https://github.com/LeeHyungGeun/react-beautiful-dnd-kr

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

1-1. DragDropContext : 드래그 앤 드롭 동작이 가능한 범위, onDragEnd(), 하위 children 필요.
- onDragEnd() : drag => drop 후 동작에 대한 함수, 함수의 argument 전달 인자를 받아서 drag/drop 된 정보 확인할 수 있다.
- onDragEnd() result type은 DropResult.

  const onDragEnd = (args: any) => { console.log(args);}
      args = 
      {
        "draggableId": "a", // drag한 Draggable의 ID
        "type": "DEFAULT",
        "source": { //출발지
            "index": 0, // Draggable의 본래 위치
            "droppableId": "one" // Draggable이 있던 Droppable의 ID
        },
        "reason": "DROP",
        "mode": "FLUID",
        "destination": { //도착지
            "droppableId": "one", // Draggable이 drop된 Droppable의 ID
            "index": 1 // Draggable의 drop된 위치
        },
        "combine": null
      }
      
const onDragEnd = ({ destination, source, draggableId }: DropResult) => {
  // 코드 작성
}

1-2. Droppable : Draggable을 드롭 할 범위, droppableId, children 필요.
-children은 ReactElement가 아닌 함수 형태로..
-droppable 내에서 DroppableProvided를 받아 하위 객체에 props로 전달한다.
- DroppableProvided에는 innerRef,placeholder,droppableProps 가 있다.

  • placeholder : Draggabled을 드래그하는 동안 position: fixed, {magic.placeholder}를 고정 시킬 요소 위치에 둘 것.
// react-beautiful-dnd/index.d.ts
export interface DroppableProvided {
    innerRef: (element: HTMLElement | null) => void;
    placeholder: React.ReactNode;
    droppableProps: DroppableProvidedProps;
}

// app.tsx
<Droppable droppableId="one">
  {(provided) => (
    <ul ref={provided.innerRef} {...provided.droppableProps}></ul>
  )}
</Droppable>

1-3. Draggable : 드래그 할 부분, draggableId, index, children 필요.
-index는 number, children은 ReactElement가 아닌 함수 형태로..
-Draggable 내에서 DraggableProvided를 받아 하위 객체에 props로 전달한다.
- DraggableProvided에는 innerRef,draggableProps,dragHandleProps 가 있다.

  • dragHandleProps : drag가 가능 할 부분 설정, drag 손잡이.
// react-beautiful-dnd/index.d.ts
export interface DraggableProvided {
    // will be removed after move to react 16
    innerRef: (element: HTMLElement | null) => void;
    draggableProps: DraggableProvidedDraggableProps;
    dragHandleProps: DraggableProvidedDragHandleProps | null | undefined;
}

// app.tsx
{(provided) => (
  <li ref={provided.innerRef} {...provided.draggableProps}> {"  "}
    <span {...provided.dragHandleProps}>🔥</span>
    Two
  </li>
)}
profile
Mong muốn trở thành chủ cuộc sống của tôi🔥.

0개의 댓글