Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any option in React-DnD, which enables drop targets based on drag object which intersects over 50% of area in drop target?

I have been working on react-dnd (which is drag and drop component). So, far drop target get identified based on mouse pointer, I am wondering is there any option to change it like, which the drop target needs to get identified based on the drag object intersects over 50% of drop target.

which is similar to jQuery UI drag and drop feature which contains 'tolerance: intersect' in droppable elements.

like image 485
veerasuthan V Avatar asked Jul 06 '17 07:07

veerasuthan V


1 Answers

Check out the sortable example of React-DnD, specifically the hover function within cardTarget:

const cardTarget = {
  hover(props, monitor, component) {
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;

    // Don't replace items with themselves
    if (dragIndex === hoverIndex) {
      return;
    }

    // Determine rectangle on screen
    const hoverBoundingRect = findDOMNode(component).getBoundingClientRect();

    // Get vertical middle
    const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;

    // Determine mouse position
    const clientOffset = monitor.getClientOffset();

    // Get pixels to the top
    const hoverClientY = clientOffset.y - hoverBoundingRect.top;

    // Only perform the move when the mouse has crossed half of the items height
    // When dragging downwards, only move when the cursor is below 50%
    // When dragging upwards, only move when the cursor is above 50%

    // Dragging downwards
    if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
      return;
    }

    // Dragging upwards
    if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
      return;
    }

    // Time to actually perform the action
    props.moveCard(dragIndex, hoverIndex);

    // Note: we're mutating the monitor item here!
    // Generally it's better to avoid mutations,
    // but it's good here for the sake of performance
    // to avoid expensive index searches.
    monitor.getItem().index = hoverIndex;
  }
};

These two lines I think is what you are looking for:

// Dragging downwards
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
  return;
}

// Dragging upwards
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
  return;
}

It checks when hovering, if the item you are hovering has crossed the 50% threshold for moving the item, and then it will perform the reorder action.

like image 151
Wolfie Avatar answered Oct 26 '22 01:10

Wolfie