ReactJS

ReactJS (16) Drag and Drop (react-beautiful-dnd 사용하기)

오리888 2023. 3. 10. 03:13

react-beautiful-dnd는 drag and drop 작업을 react 내에서 간편하게 해주는 library이다

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

우선 다운을 해주고

바로 예시를 보자

 

예)

 

코드가 좀 긴데 하나씩 설명해 보겠다


1. 우선 drag and drop 할 공간을 정해야 하는데 그 공간을 정하는 게 바로 <DragDropContext> component이다

이 component는 onDragEnd props가 필요한데 이건 유저가 element를 drag and drop 했을 때 받는 정보를 갖고 온다

 

2. 그다음 <Droppable> component는 뜻 그대로 element를 drop 할 수 있는 공간이다

이 component는 droppableId가 필요한데 Droppable component가 많을 수도 있기 때문에 각 component에 Id를 붙여줘야 한다

 

3. 마지막으로 <Draggable> component는 Droppable component와 똑같이 뜻 그대로이다

바로 drag 할 수 있는 element을 지정해 준다 따라서 각 index와 draggableId가 필요하다

 

이렇게 component들의 대한 설명을 간단하게 해 봤고 그다음엔 line 9와 12에 보이는 provided를 설명할 차례다

provided는 Droppable와 Draggable에 아주 중요한 props들을 제공해 준다

 

Droppable component에는 element를 drop 할 수 있는 기능을 넣어주고 

 

 

Draggable component에는 element를 drag 할 수 있는 기능 (draggableProps)과 drag handle (dragHandleProps)을 넣어준다

둘의 다른 점은 dragHandleProps는 말 그래도 끌 수 있는 손잡이를 준다고 생각하면 된다 손잡이가 없으면 무언갈 끌 수 없듯이 이 props가 없으면 해당 element를 마우스로 누를 수가 없다

반대로 draggableProps가 없으면 dragHandleProps가 있어도 마우스로 누를 수만 있지 끌 수는 없다

 

ref는 html element가 각 component에게 제공되어야 하기 때문에 쓰였다

 

이렇게 코드를 짠 뒤 실행시키면 Hola text를 drag and drop 할 수 있는 걸 확인할 수 있다

 

이렇게 간단하게 react-beautiful-dnd를 사용한 drag and drop 작업을 살펴보았다