This video is available to students only

Building Drag-and-Drop Logic in React With DnD's useDrag Hook

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

Previous LessonHow to Store a Drag-and-Drop Item's State in React AppStateNext LessonHow to Build a Draggable React Column Layout

Lesson Transcript

  • [00:00 - 00:05] Define the UseItemDrag hook. The dragging logic will be similar for both cards and columns.

  • [00:06 - 00:12] I suggest we move it to a custom hook. This hook will return a drag method that accepts the ref of a dragable element.

  • [00:13 - 00:24] Whenever we start dragging the item, the hook will dispatch a setDragItemAction to save the item in the AppState. When we stop dragging, it will dispatch this action again with a null as the payload.

  • [00:25 - 00:31] Create a new file inside of the SRCUtils folder. We define a new hook, UseItemDragTS.

  • [00:32 - 00:42] Expert, const, useItemDrag. It's going to be a hook where we'll get the dispatch because we want to dispatch the setDragItemAction.

  • [00:43 - 00:51] We get it from the UseState, import it from the AppState context. Then we want to use the UseDrag to get the drag function.

  • [00:52 - 01:03] Const, drag = useDrag, passing the options type is going to be the item type. The item comes from the props and has the type of drag item.

  • [01:04 - 01:18] The item is supposed to return the DragItem object and also will dispatch the SetDragItemAction. Dispatch, SetDragItem, import the section Creator and we'll return the same item.

  • [01:19 - 01:27] On end, when we stop dragging, we also dispatch SetDragItem, but we pass in null. So we reset it to null.

  • [01:28 - 01:38] So item callback is going to be triggered when we start dragging something and end callback will be triggered when we stop dragging. Now return an object with the drag field.

  • [01:39 - 01:42] It will contain the drag function from the UseDrag hook and the UseItemDrag is defined.

This lesson preview is part of the Fullstack React with TypeScript Masterclass course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

Unlock This Course

Get unlimited access to Fullstack React with TypeScript Masterclass, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course Fullstack React with TypeScript Masterclass