react-dnd
has a slightly steep learning curve, but the actual usuage of the API is quite nice.
- first you need to wrap your component around in the
DndProvider
and provide it with the HTML5Backend
becasue we’re working with web pages.
import React, { Component } from "react";
import { render } from "react-dom";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import "./style.css";
function App() {
return (
<DndProvider backend={HTML5Backend}>
<div class="app-container">....</div>
</DndProvider>
);
}
render(<App />, document.getElementById("root"));
- Now we have access to the react-dnd hooks like
useDrag
and useDrop
- with
useDrag
, we deconstruct the react-dnd
props in the first item of the array, in this example it
const [{ isDragging }, drag] = useDrag(() => ({
type: 'CARD',
item: { test: 'test', type: 'CARD' },
collect: monitor => ({
isDraggining: !!monitor.isDragging
})
}));
- the first item in the array could be any any arbitary prop which is “collected” by the
collect
callback function.