React dnd library wont work at all
I want to apply react sortable capabilities by drag in my own project. So installed and configure react dnd using :
npm install react-dnd-html5-backend
command . But when I write a component code . It was not work at all:
import React from "react";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import { useDrag } from "react-dnd";
export default function Test() {
const [data, setData] = React.useState(["A", "B", "C", "D"]);
return (
<DndProvider backend={HTML5Backend}>
{data.map((item, index) => (
<ShowItem item={item} key={item} />
))}
</DndProvider>
);
}
const ShowItem = ({ item }: { item: string }) => {
const [{ isDragging }, dragRef] = useDrag(
() => ({
type: "CARD",
item,
collect: (monitor) => ({
isDragging: !!monitor.isDragging(),
}),
}),
[item]
);
return (
<div
ref={dragRef}
style={{
width: "100px",
height: "100px",
background: "white",
margin: "10px",
opacity: isDragging ? 0.5 : 1,
cursor: "grab", // Add cursor style to indicate draggable
}}
>
{item}
</div>
);
};
You've made your cards draggable, but they also need to be droppable.
The React DnD docs have an example of how to make a sortable list here: https://react-dnd.github.io/react-dnd/examples/sortable/simple
The linked sandbox on that page has everything you're looking for I think: https://codesandbox.io/s/github/react-dnd/react-dnd/tree/gh-pages/examples_js/04-sortable/simple?from-embed=&file=/src/index.js
Could probably just copy/paste the above sandbox code, but if you wanted to apply them to your example in-place, the main changes would be:
Testthat handles updating the data order and is passed down toShowItemuseDrophook to yourShowItemcomponent that implements your new data update function fromTestand anything else you want for good UX (see the sandbox for examples)refusing React'suseRef, then apply bothdraganddropto it, then apply that to your returneddivinShowItem