Last active
April 24, 2020 02:05
-
-
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`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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