How do I run React dnd sample project

155 Views Asked by At

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>
  );
};

1

There are 1 best solutions below

0
GiorgiosJames On

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:

  • Function in Test that handles updating the data order and is passed down to ShowItem
  • Add a useDrop hook to your ShowItem component that implements your new data update function from Test and anything else you want for good UX (see the sandbox for examples)
  • Generate a bare ref using React's useRef, then apply both drag and drop to it, then apply that to your returned div in ShowItem