Just Do IT!
[React] react-beautiful-dnd를 이용한 Drag and Drop 구현하기 본문
캠프에서 프로젝트 할 때 블로그에 정리해두려고 적어두었던 것들 중 하나를 드디어...쓰게 되었다...ㅋㅋㅋ
최종 프로젝트 닐리리 할 때 적어둔 라이브러리인데, 개인프로젝트나 다른 프로젝트에서도 사용할 것 같아서 이번 기회에 정리하려고 한다!
react-beautiful-dnd란?
드래그 앤 드롭 기능을 보다 더 편리하게 구현할 수 있도록 만든 라이브러리이다.
https://www.npmjs.com/package/react-beautiful-dnd
react-beautiful-dnd
Beautiful and accessible drag and drop for lists with React. Latest version: 13.1.1, last published: a year ago. Start using react-beautiful-dnd in your project by running `npm i react-beautiful-dnd`. There are 1689 other projects in the npm registry using
www.npmjs.com
위의 사이트에서 자세히 볼 수 있다.
깃허브 링크도 있음!
https://github.com/atlassian/react-beautiful-dnd
GitHub - atlassian/react-beautiful-dnd: Beautiful and accessible drag and drop for lists with React
Beautiful and accessible drag and drop for lists with React - GitHub - atlassian/react-beautiful-dnd: Beautiful and accessible drag and drop for lists with React
github.com
나는 깃허브 리드미 보고 라이브러리 보는 게 더 편했었다.
설치
npm install react-beautiful-dnd
npm install --save @types/react-beautiful-dnd # typescript 버전
타입스크립트 버전으로 사용했었기에 타입스크립트 설치 방법도 포함.
yarn 으로 설치할 수도 있지만 나는 주로 npm을 사용하기에 위의 명령어로 설치했다.
구조
DragDropContext
- Drag and Drop이 일어나는 전체영역이다.
- Droppable, Dragpable 이 지정된 영역을 포함 하고 있어야하며, 동작의 핵심이 되는 onDragEnd={...},onDragStart={...}두 가지의 함수를 바인딩 하기 때문에 반드시 설정해줘야 하는 부분이다.
Droppable
- Drop이 일어나는(가능한) 영역이다.
- 이 영역에서 Item을 Drop할 경우에 DragDropContext 바인딩 된 onDragEnd={...} 함수가 동작하며 최종적인 Drag and Drop 동작에 대한 dom을 그려주기에 필수적으로 영역을 지정해줘야한다.
- droppableId 를 필수적으로 입력해줘야 한다.
- provided는 provided.innerRef를 참조하여 동작을 실행하는 매개변수 이기에 반드시 들어가야하는 사항이다.
- snapshot은 동작시 dom 이벤트에 대하여 적용될 style 참조를 뜻한다. 생략 가능하다.
Draggable
- Drag가 일어나는 요소들으로 Droppable 영역 안에서 움직을 요소들을 정해준다.
- Drag이벤트가 시작되면 DragDropContext 바인딩 된 onDragStart={...}가 동작한다.
- draggableId를 필수적으로 받아와야하는데 Droppable 영역에서는 DND가 일어날 영역의 고유값을 입력해 주었다면 Draggable에서는 움직일 요소들이 가지는 고유값을 입력해 주어야한다.
간단한 예시
import { Droppable } from 'react-beautiful-dnd';
<Droppable
droppableId="droppable-1"
type="PERSON"
>
{(provided, snapshot) => (
<div
ref={provided.innerRef}
style={{backgroundColor: snapshot.isDraggingOver ? 'blue' : 'grey'}}
>
I am a droppable!
</div>
)}
</Droppable>
깃허브 리드미에 적힌 간단한 예시이다.
위의 구조를 생각하고 구현하면 처음부터 구현하는 것보다는 편하게 드래그앤드롭을 구현할 수 있다!
방학도 끝났고...이제 미뤘던 정리들을 할 차례인데 또 늦어버렸다 ㅋㅋ
이것도 꽤 오래 전에 알고 프로젝트에 적용했었는데 그 프로젝트가 엎어지는 바람에 쓰지 못했던 기억이 있다.
그냥 정리만 해두고 다음 프로젝트에 써보고 내용을 조금 더 추가해야겠다.
'개발 공부 > React' 카테고리의 다른 글
리액트 custom hook으로 Pagination 구현하기 (0) | 2023.10.10 |
---|---|
리액트 custom hook으로 모달창 구현하기 (useModal) (1) | 2023.10.02 |
[React] Flux 패턴이란? (0) | 2023.06.13 |
[React] state와 props (0) | 2023.04.05 |
[React] react-fullpage 라이브러리 (fullpage scroll) (0) | 2023.02.01 |