7

I'm trying to make a Trello clone using React react-dnd. Just by entering the code below I get the error

 const [{ isDragging }, dragRef] = useDrag({
    item: { type: "CARD" },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

I get the following error

spec.type must be defined

invariant
C:/Users/lucca/Documents/GitHub/2B-task/src/index.ts:28
 25  |   );
  26 | } else {
  27 |   let argIndex = 0;
> 28 |   error = new Error(
     | ^  29 |     format.replace(/%s/g, function() {
  30 |       return args[argIndex++];
  31 |     })
Hora
  • 162
  • 1
  • 8

5 Answers5

11

FIX:

In version ^14 of React DnD the API format changed. The type is now decoupled from item:

// Pre-v14
useDrag({
   // item defined here to get a type
   item: { type: BOX } },
   // ...but the actual item is created here
   begin: () => ({ id })
})

// v14
useDrag({
   // type is now listed by itself, not inside of item
   type: BOX,
   item: () => ({id})
})

TLDR:

Documentation on this: https://github.com/react-dnd/react-dnd/releases/tag/v14.0.0

This should work on all recent React versions. My versions are:

"react": "^17.0.2",
"react-dnd": "^15.0.2",
"react-dnd-html5-backend": "^15.0.2",
GavinBelson
  • 2,514
  • 25
  • 36
6

Here type should be passed as a prop of useDrag. Please make sure you are passing the same type CARD in useDrop as well in accept. You can find more references here.

const [{ isDragging }, dragRef] = useDrag({
    type: "CARD",
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

 const [collectedProps, drop] = useDrop({
    accept: "CARD",
    collect: (monitor: any) => { ... },
    ...
});

avatar
  • 161
  • 1
  • 6
2

As in another answer given, you need to make the type a property of the useDrag object.

const [{isDragging}, drag] = useDrag({
        type: "CARD",
        collect: monitor => ({
          isDragging: !!monitor.isDragging()
        })
      })
Tristan Trainer
  • 2,770
  • 2
  • 17
  • 33
1

I had the same issue after react-dnd upgrade. Working again after Rollback.

Opening an issue with React-dnd might help to find the root cause.

Edit: Change was made for 14.0 release : https://github.com/react-dnd/react-dnd/releases/tag/v14.0.0

user2068020
  • 17
  • 1
  • 5
1

Change version "react": "^16.13.1", "react-dnd": "^11.1.3", "react-dnd-html5-backend": "^11.1.3",

  • 1
    Please refrain from answering questions with just a code snippet. [Check this article](https://stackoverflow.com/help/how-to-answer) to learn how to write an answer. – Andrea Olivato Jun 04 '21 at 09:31