React-dnd: How to know `isDragging` inside a `DropTarget`?

Created on 1 Feb 2016  ·  4Comments  ·  Source: react-dnd/react-dnd

I want to show drop targets when some source is dragged, and hide all targets when nothing is dragged.
However the isDragging monitor is only provided for source.
Any way to know isDragging inside a DropTarget?

question

Most helpful comment

Since source is required to return an item when beginDrag, I implemented a working version of isDragging like this:

import React from 'react';
import { ItemTypes } from '../../constants';
import { DropTarget } from 'react-dnd';

const widgetTarget = {
  drop(props) {
    // moveKnight(props.x, props.y);
  }
};

function collect(connect, monitor) {
  const item = monitor.getItem();
  return {
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver(),
    item: item,
    isDragging: !!item,
  };
}

@DropTarget(ItemTypes.WIDGET, widgetTarget, collect)
export default class WidgetHolder extends React.Component {
  render() {
    const {
      connectDropTarget,
      isDragging,
      isOver,
      item
    } = this.props;
    const style = {
      width: '100%',
      visibility: isDragging? 'visible': 'hidden',
      backgroundColor: isOver? 'green': 'inherit',
    };
    return connectDropTarget(
      <div style={style}>
        Drop here
      </div>
    );
  }
};

@wdhorton thanks for the reference example. I will ckeck it!

All 4 comments

I would check the source for the Simple Sortable example. It sounds like you want to do something similar to what they did with hover in the cardTarget.

Since source is required to return an item when beginDrag, I implemented a working version of isDragging like this:

import React from 'react';
import { ItemTypes } from '../../constants';
import { DropTarget } from 'react-dnd';

const widgetTarget = {
  drop(props) {
    // moveKnight(props.x, props.y);
  }
};

function collect(connect, monitor) {
  const item = monitor.getItem();
  return {
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver(),
    item: item,
    isDragging: !!item,
  };
}

@DropTarget(ItemTypes.WIDGET, widgetTarget, collect)
export default class WidgetHolder extends React.Component {
  render() {
    const {
      connectDropTarget,
      isDragging,
      isOver,
      item
    } = this.props;
    const style = {
      width: '100%',
      visibility: isDragging? 'visible': 'hidden',
      backgroundColor: isOver? 'green': 'inherit',
    };
    return connectDropTarget(
      <div style={style}>
        Drop here
      </div>
    );
  }
};

@wdhorton thanks for the reference example. I will ckeck it!

Looking at your code, you can define a hover() function within your existing widgetTarget object. It will have the signature hover(props, monitor, component), which you can use as you wish.

You can check monitor.getItem(). If it exists, then you are dragging. Otherwise not.

Was this page helpful?
0 / 5 - 0 ratings