codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

React Drag and Drop: An Easier Tutorial

John Tucker
codeburst
Published in
5 min readJun 1, 2018

...
export default DragDropContext(HTML5Backend)(Board);
export const ITEM = 'ITEM';
...const Target = ({ connectDropTarget, highlighted, shape }) => (
connectDropTarget(
<div
className={`board__targets__target board__targets__target--${shape}`}
style={{ backgroundColor: highlighted ? 'black' : 'gray' }}
/>
)
);
Target.propTypes = {
connectDropTarget: PropTypes.func.isRequired,
highlighted: PropTypes.bool.isRequired,
shape: PropTypes.string.isRequired,
}
...
...
const target = {
drop(props) {
const { shape } = props;
return ({
shape,
});
}
}
const collect = (connect, monitor) => ({
connectDropTarget: connect.dropTarget(),
highlighted: monitor.canDrop(),
});
export default DropTarget(ITEM, target, collect)(Target);
...
const Source = ({ color, connectDragSource, isDragging }) => (
connectDragSource(
<div
className="board__sources__source"
style={{
backgroundColor: color,
opacity: isDragging ? 0.25 : 1,
}}
/>
)
);
Source.propTypes = {
color: PropTypes.string.isRequired,
connectDragSource: PropTypes.func.isRequired,
isDragging: PropTypes.bool.isRequired,
}
...
...
const source = {
beginDrag(props) {
const { color } = props;
return ({
color,
});
},
endDrag(props, monitor) {
if (!monitor.didDrop()) {
return;
}
const { onDrop } = props;
const { color } = monitor.getItem();
const { shape } = monitor.getDropResult();
onDrop(color, shape);
},
};
const collect = (connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging(),
});
export default DragSource(ITEM, source, collect)(Source);

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by John Tucker

Broad infrastructure, development, and soft-skill background

Responses (2)

Write a response