Web-Frontend/React.js

[React.js] react-beautiful-dnd

서노리 2023. 6. 15. 03:10
반응형

react-beautiful-dnd

React로 쉽게 드래그 앤 드롭 리스트를 만들 수 있도록 도와주는 패키지이다.

npm i react-beautiful-dnd
npm i --save-dev @types/react-beautiful-dnd

DragDropContext

DragDropContext는 드래그 앤 드롭을 가능하게 하고자 하는 영역을 감싸주는 컨테이너이다. 자식 컴포넌트와 드래그를 끝낸 시점에 불려지는 함수인 onDragEnd라는 prop이 필수로 들어간다.

 

Droppable

Droppable은 유저가 어떤 것을 드롭할 수 있는 영역을 의미하며, droppableId라는 prop과 함수 형식의 자식 요소를 필수로 넣어줘야한다. Droppable의 자식 요소에 전달되는 magic이라고 불리는 prop은 DroppableProvided이며 다음과 같은 prop들이 정의되어있다. 

 

Draggable

Draggable은 유저가 어떤 것을 드래그할 수 있는 영역을 의미하며, draggableId라는 prop과,함수 형식의 자식 요소를 필수로 넣어줘야한다. Draggable의 자식 요소에 전달되는 magic이라고 불리는 prop은 DroppableProvided이며 다음과 같은 prop들이 정의되어있다.

  • draggableProps : 요소 전체를 드래그 하는 것을 의미 (요소가 기본적으로 드래그 되기를 원한다면 사용하면됨.)
  • dragHandleProps : 원하는 위치에서 드래그해서 옮기는 것을 의미.

 

import {DragDropContext, Drappable} from 'react-beautiful-dnd';

const lists = ['a','b','c','d','e','f',];

<DragDropContext onDradEnd={onDradEnd}>
  <div>
    <Drappable drappableId="one">
    {(magic) =>
      <ul ref={magic.innerRef} {...magic.droppableProps}>
        {lists.map((list, index) => 
          <Draggable draggableId={list} index={index} key={toDo}>
          {(magic) =>
            <li
              ref={magic.innerRef}
              {...magic.draggableProps}
              {...magic.dragHandleProps}
            >
              {list}
            </li>
          }
        </Draggable>
        )}
        {magic.placeholder}
      </ul>
    }
    </Drappable>
  </div>
</DragDropContext>

 

※ placeholder

Draggable 요소를 드래그 하는 동안 Dropaable 리스트의 크기가 작아지는 것을 방지해주기 위해 추가해주어야한다.


onDragEnd 함수 작성

여기까지 설정하면 해당 요소들을 드래그할 수 있다. 하지만 onDragEnd에 아무것도 해주지 않았기 때문에 드롭이 끝났을 때 다시 원래 자리로 돌아가게된다. 이를 위해 onDragEnd 함수에서 요소들을 재정렬하는 코드를 작성해주어야한다.

 

위는 onDragEnd의 타입으로 함수가 어떻게 생겼는지 알 수 있다. DropResult도 열어서 살펴보면 destination, source 등의 prop들이 있는 것을 알 수 있다. 해당 prop들을 이용해서 재정렬 함수를 만들 수 있다.

 


※ 드래그, 드랍 중인 컴포넌트의 스타일링

Droppable, Draggable의 자식요소에 전달되는 snapshot에 있는 다양한 속성들을 통해 드래그 드랍 중인 컴포넌트들의 상태에 대해 알 수 있다. 


 

반응형

'Web-Frontend > React.js' 카테고리의 다른 글

[React.js] Redux-Toolkit  (0) 2023.07.20
[React.js] Redux  (0) 2023.07.20
[React.js] React에서 Font Awesome 사용하기  (0) 2023.06.03
[React.js] Recoil - Selector  (0) 2023.04.18
[React.js] React Hook Form  (0) 2023.04.05