프로그래밍/ReactJS

react-beautiful-dnd 설치 및 사용

타코코딩 2023. 11. 10. 09:59

 

react-beautiful-dndReact
애플리케이션에서 드래그 앤 드롭 기능을 구현하는 데 널리 사용되는 라이브러리입니다. 복잡한 드래그 앤 드롭 인터페이스를 쉽게 만들 수 있도록 일련의 구성 요소와 유틸리티를 제공합니다.
npm i react-beautiful-dnd
npm i --save-dev @types/react-beautiful-dnd

설치 후 typescript에서 react-beautiful-dnd를 인식시켜줘야 함

import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd";
function App() {
const [minutes, setMinutes] = useRecoilState(minuteState);
const onMinutesChange = (event: React.FormEvent<HTMLInputElement>) => {
setMinutes(+event.currentTarget.value);
};
const onDragEnd = () => {};
return (
<div className="App">
<DragDropContext onDragEnd={onDragEnd}>
<div>
<Droppable droppableId="one">
{() => (
<ul>
<Draggable draggableId="first" index={0}>
{() => <li>one</li>}
</Draggable>
<Draggable draggableId="second" index={1}>
{() => <li>two</li>}
</Draggable>
</ul>
)}
</Droppable>
</div>
</DragDropContext>
</div>
);
}

 

DragDropContext < Draggable < Droppable 순서로 상위 <하위 요소이다

 


 

npm install react-beautiful-dnd

이제 간단한 드래그 가능한 목록을 만들어 보겠습니다.

// App.jㄴ
import React, { useState } from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
const initialItems = [
{ id: '1', content: 'Item 1' },
{ id: '2', content: 'Item 2' },
{ id: '3', content: 'Item 3' },
];
const App = () => {
const [items, setItems] = useState(initialItems);
const onDragEnd = (result) => {
if (!result.destination) return; // dropped outside the list
const updatedItems = Array.from(items);
const [movedItem] = updatedItems.splice(result.source.index, 1);
updatedItems.splice(result.destination.index, 0, movedItem)
setItems(updatedItems);
};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="droppable">
{(provided) => (
<ul {...provided.droppableProps} ref={provided.innerRef}>
{items.map((item, index) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided) => (
<li
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{item.content}
</li>
)}
</Draggable>
))}
{provided.placeholder}
</ul>
)}
</Droppable>
</DragDropContext>
);
};
export default App;

이 예에서는 다음과 같습니다.

 

우리는 DragDropContext, Droppable, Draggable() import 합니다 

 

상태에서는 몇 가지 초기 항목을 설정했습니다.

 

onDragEnd 끌어서.

 

명령문 내에서 구성 요소를 최상위 컨테이너로 return사용합니다 . 우리 함수를 참조하는 prop이 DragDropContext필요합니다 .onDragEndonDragEnd

 

내에서 배열을 DroppableDroppable 통해 매핑하여 각 항목에 대한 구성 요소를 items만듭니다 . 함수에 전달된 prop에는 요소를 드래그 가능하게 만드는 데 필요한 propsref가 포함되어 있습니다 Draggable.provided

 

onDragEnd함수는 개체를 사용하여 result드래그된 항목의 소스 및 대상 인덱스를 결정합니다. 그런 다음 항목의 새 순서를 반영하도록 상태를 업데이트합니다.

 

react-beautiful-dnd고급 기능 및 사용자 정의 옵션에 대해서는 공식 문서를 확인하세요 : https://github.com/atlassian/react-beautiful-dnd