Ad

ReactDnD, Enable To Create A Simple DragDropContext - DragSource Example

- 1 answer

I am new to React and following this tutorial for adding Drag'n'Drop to my application

I was following the tutorial step by step to create a chess board with a draggable knight piece, but couldn't get it to work (Still unable to drag the knight)

    // imports
var {DragSource, DragDropContext} = ReactDnD;

var knightSource = {
    beginDrag: function (props) {
        return {};
    }
};

function collect(connect, monitor) {
    return {
        connectDragSource: connect.dragSource(),
        isDragging: monitor.isDragging()
    }
}

var Knight = DragSource("knight", knightSource, collect)(React.createClass({
    render() {
        var style = {
            cursor: 'move',
            fontSize: 25
        }
        return(
            <div style={style}>♘</div>
        );
    }
}));


var Board = DragDropContext(HTML5Backend)(React.createClass({
    render() {
        var style = {
            width: '500px',
            height: '500px',
            border: '1px solid black',
            boxShadow: '4px 2px 2px black'
        }
        return (
            <div style={style}>
                <Knight/>
            </div>
        );
    }
}));

ReactDOM.render(
    <Board/>,
    document.getElementById('ex13')
);

});

Can anyone explain what I am doing wrong?

Ad

Answer

You are wrapping the Knight component with the DragSource(itemType, source, collect) properly, but within then knight component you need to wrap what render returns with this.props.connectDragSource, similar to the tutorial (I've just copied it here):

render: function () {
  var connectDragSource = this.props.connectDragSource;
  var isDragging = this.props.isDragging;

  return connectDragSource(
    <div style={{
      opacity: isDragging ? 0.5 : 1,
      fontSize: 25,
      fontWeight: 'bold',
      cursor: 'move'
    }}>
      ♘
    </div>
  );
}

Note how he grabs the connectDragSource from the props (and injected by the collect function) and then wraps the div tag with it.

Ad
source: stackoverflow.com
Ad