Search code examples
react-dnd

What does getHandlerId() do and how to use it?


Some of the react-dnd examples use a getHandlerId() method.

For example in the simple example of a sortable list, the Card.tsx function:

  • Collects a handlerId from the monitor object within the useDrop method

    collect(monitor) {
      return {
        handlerId: monitor.getHandlerId(),
      }
    },
    
  • Returns that as an element of the "collected props"

    const [{ handlerId }, drop] = useDrop<
    
  • Uses it to initialize an HTML attribute named data-handler-id

    <div ref={ref} style={{ ...style, opacity }} data-handler-id={handlerId}>
    

What is this Id and why is it used?

What uses the data-handler-id attribute?

I'd expect to see getHandlerId() described in the API documentation as a method of the DropTargetMonitor (but it isn't).


Solution

  • I didn't dive deep into it but for me this information was enough to continue using it:

    1. If you remove this data-handler-id, everything continue working but with some issues (item sometimes flickers, it doesn't go to another place as smoothly as it does with data-handler-id)
    2. Here is an open issue https://github.com/react-dnd/react-dnd/issues/2621 about low performance, and this comment suggests to use handler id: https://github.com/react-dnd/react-dnd/issues/2621#issuecomment-847316022
    3. As you can see in code https://github.com/react-dnd/react-dnd/search?q=handlerId&type=code, handler id is using for proper definition of drop item so it seems better to use it even if you don't have a lot of elements.