Skip to content

Instantly share code, notes, and snippets.

@dwaltrip
Last active April 24, 2020 02:05
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dwaltrip/005a520aeaebe328a8a33998be2babc4 to your computer and use it in GitHub Desktop.
Save dwaltrip/005a520aeaebe328a8a33998be2babc4 to your computer and use it in GitHub Desktop.
Wrapping react-beautiful-dnd components so that we can pass `onDragEnd` directly to each `Droppable`
import {
DragDropContext as RealDragDropContext,
Droppable as RealDroppable,
Draggable
} from 'react-beautiful-dnd';
import React, { Component } from 'react';
const DroppableManager = {
_onDragEndLookup: {},
register(droppableId, onDragEnd) {
assert(!(droppableId in this._onDragEndLookup),
`droppableId="${droppableId}" has already been used. droppableIds should be unique.`);
this._onDragEndLookup[droppableId] = onDragEnd;
},
unregister(droppableId) {
delete this._onDragEndLookup[droppableId];
},
getOnDragEnd(droppableId) {
return this._onDragEndLookup[droppableId]
}
};
class Droppable extends Component {
componentDidMount() {
const { droppableId, onDragEnd } = this.props;
assert(onDragEnd,
`Droppable with droppableId="${droppableId}"" is missing 'onDragEnd' hook.`);
DroppableManager.register(droppableId, onDragEnd);
}
componentWillUnmount() {
const { droppableId } = this.props;
DroppableManager.unregister(droppableId);
}
render() {
const { children, ...otherProps } = this.props;
return (
<RealDroppable {...otherProps}>
{children}
</RealDroppable>
);
}
}
class DragDropContext extends Component {
globalOnDragEnd = (result)=> {
const { type, source, destination } = result;
if (!destination) { return; }
if (source.droppableId === destination.droppableId && source.index === destination.index) {
return;
}
const onDragEnd = DroppableManager.getOnDragEnd(destination.droppableId);
onDragEnd(result);
if (this.props.onDragEnd) {
this.props.onDragEnd(result);
}
};
render() {
return (
<RealDragDropContext onDragEnd={this.globalOnDragEnd}>
{this.props.children}
</RealDragDropContext>
);
}
}
export { Droppable, DragDropContext, Draggable };
// ---------------------------------------------
function assert(condition, message) {
if (!condition) {
throw new Error(message || 'Assertion failed');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment