npm i react-beautiful-dnd
npm i --save-dev @types/react-beautiful-dnd
DragDropContext์ Drag and Drop์ด ์ผ์ด๋๋ ์ ์ฒด์์ญ.
Droppable, Dragpable ์ด ์ง์ ๋ ์์ญ์ ํฌํจ ํ๊ณ ์์ด์ผํ๋ฉฐ,
์ ์ ๊ฐ ๋๋๊ทธ๋ฅผ ๋๋ธ ์์ ์ ๋ถ๋ ค์ง๋onDragEnd={}
ํจ์๋ฅผ ํ์๋ก ๊ฐ์ง๊ณ ์์ด์ผํ๋ค.
์ฌ์ฉ
{ import { DragDropContext } from "react-beautiful-dnd";
function App() {
const onDragEnd = (...) => {...};
return (
<DragDropContext onDragEnd={onDragEnd}>
...
</DragDropContext>
)
}
Dropํ ์ ์๋ ์์ญ(Drop์ด ์ด๋ฃจ์ด์ง๋ ์์ญ)
์ ์ ๊ฐ ๋๋กญํ ์ ์๋ ์์ญ์ด ์ฌ๋ฌ๊ฐ์ผ ์ ์์ผ๋ฏ๋ก,
๊ณ ์ ํ ๊ฐ์ ๊ฐ์ง๊ณ ์๋ droppableId
prop์ ํ์๋ก ๊ฐ์ง๊ณ ์์ด์ผ ํ๋ค.
Droppable ์ children ์ react ์์์ด๋ฉด ์๋๋ฉฐ, ํจ์์ฌ์ผํ๋ค.
์ฌ์ฉ
{ import { DragDropContext, Droppable } from "react-beautiful-dnd";
function App() {
const onDragEnd = (...) => {...};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="one">
{() => <ul></ul>}
</Droppable>
</DragDropContext>
)
}
onDragStart={...}
๊ฐ ๋์ํ๋ค.draggableId
, index
prop ์ ํ์๋ก ๊ฐ์ง๋ค.{ import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
function App() {
const onDragEnd = (...) => {...};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="one">
{() =>
<ul>
<Draggable draggableId="first" index={0}>
{() => <li>One</li>}
</Draggable>
<Draggable draggableId="second" index={1}>
{() => <li>Two</li>}
</Draggable>
</ul>}
</Droppable>
</DragDropContext>
)
}
droppable
,draggable
์ ์ฒซ๋ฒ์งธ ๋งค๊ฐ๋ณ์, provided
provided.innerRef
๋ฅผ ์ฐธ์กฐํ์ฌ ๋์์ ์คํํ๋ ๋งค๊ฐ๋ณ์ ์ด๊ธฐ์droppable
draggable
{ import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
function App() {
const onDragEnd = (...) => {...};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="one">
{(magic) =>
<ul ref={magic.innerRef} {...magic.droppableProps}>
<Draggable draggableId="first" index={0}>
{(magic) =>
<li ref={magic.innerRef} {...magic.draggableProps}>
One
</li>
}
</Draggable>
</ul>}
</Droppable>
</DragDropContext>
)
}
const toDos = ["a", "b", "c", "d", "e", "f"];
Droppable
์ provided
๋งค๊ฐ๋ณ์์ ์์ ์๋ placeholder
๋ฅผ ์ฌ์ฉํด์ฃผ์.Draggable ์๋ฆฌ๋จผํธ๋ฅผ dragํ๋ ๋์ position: fixed(์์ญ์ ๊ณ ์ ์ํด)๋ฅผ ์ ์ฉํ๋ค.
Draggable์ ๋๋๊ทธํ ๋ Droppable ๋ฆฌ์คํธ๊ฐ ์์์ง๋ ๊ฒ์ ๋ฐฉ์งํ๊ธฐ ์ํด ํ์ํ๋ค.
์ต์ข ์ฝ๋
function App() {
const onDragEnd = () => {...};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Wrapper>
<Boards>
<Droppable droppableId="one">
{(magic) => (
<Board ref={magic.innerRef} {...magic.droppableProps}>
{toDos.map((toDo, index) => (
<Draggable draggableId={toDo} index={index}>
{(magic) => (
<Card
ref={magic.innerRef}
{...magic.dragHandleProps}
{...magic.draggableProps}
>
{toDo}
</Card>
)}
</Draggable>
))}
{magic.placeholder}
</Board>
)}
</Droppable>
</Boards>
</Wrapper>
</DragDropContext>
);
}