Beautiful DND는 리액트 애플리케이션에서 드래그 앤 드롭 기능을 구현하는 데 사용되는 라이브러리입니다. 사용자가 요소를 마우스로 드래그하고 원하는 위치로 놓을 수 있는 강력한 기능을 제공합니다. Beautiful DND는 사용하기 쉽고 유연하며 성능도 우수하게 유지합니다.
설치
Beautiful DND를 사용하기 위해서는 npm이나 yarn을 사용하여 패키지를 설치해야 합니다. 아래의 명령어를 사용하여 설치합니다.
npm install react-beautiful-dnd
또는
yarn add react-beautiful-dnd
사용법
Beautiful DND를 사용하려면 먼저 드래그 가능한 요소와 드롭 영역을 정의해야 합니다. 예를 들어, todo 리스트의 항목을 드래그하여 순서를 변경하고 싶다고 가정해봅시다.
import React from 'react';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
class TodoList extends React.Component {
state = {
todos: [
{ id: '1', content: 'Buy groceries' },
{ id: '2', content: 'Do laundry' },
{ id: '3', content: 'Clean the house' },
],
};
handleDragEnd = (result) => {
// 드래그 앤 드롭 완료 시 실행되는 함수
if (!result.destination) return; // 드롭 위치가 없을 경우 함수 종료
const todos = Array.from(this.state.todos);
const [removed] = todos.splice(result.source.index, 1); // 드래그된 요소 제거
todos.splice(result.destination.index, 0, removed); // 드롭 위치에 요소 추가
this.setState({ todos });
};
render() {
return (
<DragDropContext onDragEnd={this.handleDragEnd}>
<Droppable droppableId="todos">
{(provided) => (
<ul {...provided.droppableProps} ref={provided.innerRef}>
{this.state.todos.map((todo, index) => (
<Draggable key={todo.id} draggableId={todo.id} index={index}>
{(provided) => (
<li
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
>
{todo.content}
</li>
)}
</Draggable>
))}
{provided.placeholder}
</ul>
)}
</Droppable>
</DragDropContext>
);
}
}
export default TodoList;
위의 예제 코드에서는 Beautiful DND의 DragDropContext
, Draggable
, Droppable
컴포넌트를 사용하여 드래그 앤 드롭 기능을 구현하였습니다. DragDropContext
는 드래그 앤 드롭 이벤트를 처리하는 컨텍스트를 생성하고, Droppable
은 드롭 영역을 정의하며, Draggable
은 드래그 가능한 요소를 정의합니다.
Draggable
컴포넌트 안에서는 provided.draggableProps
와 provided.dragHandleProps
를 사용하여 드래그 앤 드롭 요소의 속성을 설정합니다. Droppable
컴포넌트는 provided.droppableProps
와 provided.innerRef
를 사용하여 드롭 영역의 속성을 설정합니다.
handleDragEnd
함수는 드래그 앤 드롭이 완료되었을 때 실행되는 함수로, 드래그된 요소를 제거하고 드롭 위치에 새로 추가하는 역할을 합니다.
결론
Beautiful DND는 리액트 애플리케이션에서 드래그 앤 드롭 기능을 구현하는 데 사용되는 훌륭한 라이브러리입니다. 간단한 예제를 통해 사용법을 확인하고, 실제 프로젝트에서 활용해보세요. 자세한 내용은 공식 문서를 참고하시기 바랍니다.