드래그 앤 드롭 기능은 웹 개발에서 많이 사용되는 기능 중 하나입니다. 이 기능을 사용하면 사용자가 요소를 클릭하고 드래그하여 다른 위치로 이동시킬 수 있습니다. Beautiful Dnd는 React용 드래그 앤 드롭 라이브러리로 유명합니다. 이 라이브러리를 사용하여 그리드를 만들어보겠습니다.
Beautiful Dnd 설치
Beautiful Dnd를 사용하기 위해서는 먼저 패키지를 설치해야 합니다. 다음 커맨드를 사용하여 설치합니다.
npm install react-beautiful-dnd
또는 yarn을 사용할 경우,
yarn add react-beautiful-dnd
Beautiful Dnd를 사용한 그리드 만들기
먼저 Beautiful Dnd의 필수 컴포넌트들을 import해야 합니다.
import React, { useState } from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
이제 그리드 컴포넌트를 생성하고 Beautiful Dnd를 적용합니다. 예를 들어 4x4 크기의 그리드를 만들어볼 수 있습니다.
const Grid = () => {
const [gridData, setGridData] = useState([
{ id: '1', text: '1' },
{ id: '2', text: '2' },
{ id: '3', text: '3' },
{ id: '4', text: '4' },
{ id: '5', text: '5' },
{ id: '6', text: '6' },
{ id: '7', text: '7' },
{ id: '8', text: '8' },
{ id: '9', text: '9' },
{ id: '10', text: '10' },
{ id: '11', text: '11' },
{ id: '12', text: '12' },
{ id: '13', text: '13' },
{ id: '14', text: '14' },
{ id: '15', text: '15' },
{ id: '16', text: '16' }
]);
const handleDragEnd = (result) => {
if (!result.destination) return;
const items = Array.from(gridData);
const [reorderedItem] = items.splice(result.source.index, 1);
items.splice(result.destination.index, 0, reorderedItem);
setGridData(items);
};
return (
<DragDropContext onDragEnd={handleDragEnd}>
<Droppable droppableId="grid">
{(provided) => (
<div ref={provided.innerRef} {...provided.droppableProps}>
{gridData.map((item, index) => (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
className="grid-item"
>
{item.text}
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
);
};
위의 코드에서는 gridData
배열을 사용하여 그리드 아이템을 표시하고, handleDragEnd
함수를 사용하여 드래그 앤 드롭 이벤트에 대한 처리를 수행합니다. DragDropContext
, Droppable
, Draggable
컴포넌트는 Beautiful Dnd에서 필요한 컴포넌트들입니다.
그리드 스타일링
그리드를 스타일링하려면 css를 사용하여 grid-item
클래스를 스타일링하면 됩니다.
.grid-item {
width: 100px;
height: 100px;
border: 1px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
}
이제 Grid
컴포넌트를 사용하면 드래그 앤 드롭으로 그리드를 만들 수 있습니다.
import React from 'react';
import Grid from './Grid';
const App = () => {
return (
<div>
<h1>Beautiful Dnd 그리드</h1>
<Grid />
</div>
);
};
export default App;
위 예제에서는 React를 사용하였지만, Beautiful Dnd는 다른 프레임워크와 함께도 사용할 수 있습니다.
결론
Beautiful Dnd를 사용하면 간단하게 드래그 앤 드롭 기능을 구현할 수 있으며, 그리드와 같은 다양한 레이아웃을 만들 수 있습니다. 이 라이브러리는 React와 호환되며, 설치와 사용이 간편하다는 장점이 있습니다.