[javascript] Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소 감추기
지금은 React.js를 사용 중이고, 사용자에게 요소를 드래그 앤 드롭으로 감출 수 있는 기능을 추가하고 싶다고 가정해 봅시다. Beautiful Dnd 라이브러리를 사용하여 이를 쉽게 구현할 수 있습니다. Beautiful Dnd는 드래그 앤 드롭 인터랙션을 쉽게 처리할 수 있는 기능을 제공합니다.
Beautiful Dnd 설치
먼저 Beautiful Dnd를 설치해야 합니다. npm을 사용하여 다음 명령을 실행하세요:
npm install react-beautiful-dnd
Beautiful Dnd 사용 방법
이제 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소를 감추는 기능을 구현해 보겠습니다.
- 먼저, Beautiful Dnd에서 제공하는
Draggable
과Droppable
컴포넌트를 임포트합니다.
import { Draggable, Droppable } from 'react-beautiful-dnd';
- 드래그 앤 드롭을 적용하고자 하는 컴포넌트 내에서
Droppable
컴포넌트를 사용합니다. 이 컴포넌트는 드래그 앤 드롭 될 요소의 컨테이너 역할을 합니다.
<Droppable droppableId="droppable">
{(provided, snapshot) => (
<div ref={provided.innerRef} {...provided.droppableProps}>
{/* 드래그 앤 드롭 될 요소들 */}
{/* ... */}
{provided.placeholder}
</div>
)}
</Droppable>
- 드래그 앤 드롭을 적용하고자 하는 각 요소에
Draggable
컴포넌트를 사용합니다.
<Draggable draggableId="draggable-1" index={0}>
{(provided, snapshot) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{/* 드래그 앤 드롭 될 요소의 내용 */}
{/* ... */}
</div>
)}
</Draggable>
Draggable
과Droppable
컴포넌트를 사용하여 요소를 구성한 후, Beautiful Dnd에서 제공하는onDragEnd
함수를 사용하여 드래그 앤 드롭 이벤트를 처리합니다.
const onDragEnd = (result) => {
// result에서 드래그 앤 드롭 결과를 얻을 수 있음
// 요소의 위치를 업데이트하거나 특정 동작을 수행할 수 있음
};
// ...
<DragDropContext onDragEnd={onDragEnd}>
{/* 요소와 드래그 앤 드롭을 적용한 컴포넌트 */}
{/* ... */}
</DragDropContext>
예제
다음은 Beautiful Dnd를 사용하여 드래그 앤 드롭으로 요소를 감추는 예제 코드입니다:
import React from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
const items = ['아이템 1', '아이템 2', '아이템 3'];
const App = () => {
const onDragEnd = (result) => {
// 드래그 앤 드롭 결과를 처리하는 로직
// 예를 들어, 요소의 위치를 업데이트하거나 특정 동작을 수행할 수 있음
console.log(result);
};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="droppable">
{(provided, snapshot) => (
<div ref={provided.innerRef} {...provided.droppableProps}>
{items.map((item, index) => (
<Draggable key={item} draggableId={item} index={index}>
{(provided, snapshot) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
style={{
// 드래그 중인 요소의 스타일
backgroundColor: snapshot.isDragging ? 'lightgreen' : '',
...provided.draggableProps.style
}}
>
{item}
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
);
};
export default App;
이 코드를 실행하면, 세 개의 아이템이 드래그 앤 드롭될 수 있는 컨테이너로 표시됩니다. 사용자가 아이템을 드래그하면, 아이템이 드래그 중인 컨테이너로 이동하고 배경색이 변경됩니다. onDragEnd
함수에서는 드래그 앤 드롭 결과를 처리할 수 있습니다.
Beautiful Dnd는 다양한 기능을 제공하기 때문에, 더 자세한 사용 방법과 옵션에 대해서는 공식 문서를 참고하시기 바랍니다.