Skip to content

Instantly share code, notes, and snippets.

@mockdeep
Last active August 29, 2015 14:19
Show Gist options
  • Save mockdeep/2cb109097a9f9580aeb5 to your computer and use it in GitHub Desktop.
Save mockdeep/2cb109097a9f9580aeb5 to your computer and use it in GitHub Desktop.
React DnD example simplified
(function () {
'use strict';
window.Card = React.createClass({
mixins: [ReactDND.DragDropMixin],
statics: {
configureDragDrop: function(register) {
register('card', {
dragSource: {
beginDrag: function(component) {
return { item: { id: component.props.id } };
}
},
dropTarget: {
over: function(component, item) {
component.props.moveCard(item.id, component.props.id);
}
}
});
}
},
render: function () {
var dragSource = this.dragSourceFor('card');
var dropTarget = this.dropTargetFor('card');
var isDragging = this.getDragState('card').isDragging;
var style = {opacity: isDragging ? 0 : 1};
return (
<div {...dragSource} {...dropTarget} style={style}>
{this.props.text}
</div>
);
}
});
})();
(function () {
'use strict';
window.Container = React.createClass({
getInitialState: function () {
return {
cards: [
{ id: 1, text: 'Write a cool JS library' },
{ id: 2, text: 'Make it generic enough' },
{ id: 3, text: 'Write README' },
{ id: 4, text: 'Create some examples' },
{ id: 5, text: 'Spam in Twitter and IRC to promote it' },
{ id: 6, text: '???' },
{ id: 7, text: 'PROFIT' }
]
};
},
moveCard: function (id, afterId) {
// No ReactDND in here, just moving cards around in plain JS
var cards = this.state.cards;
var card = cards.filter(function (c) { return c.id === id; })[0];
var afterCard = cards.filter(function (c) { return c.id === afterId })[0];
var cardIndex = cards.indexOf(card);
var afterIndex = cards.indexOf(afterCard);
// duplicate `cards`
var newCards = cards.slice();
// take moved card out of list
newCards.splice(cardIndex, 1);
// put card back in at new position
newCards.splice(afterIndex, 0, card);
this.setState({cards: newCards});
},
cardList: function () {
var renderCard = this.renderCard;
return this.state.cards.map(function (card) { return renderCard(card) });
},
renderCard: function (card) {
var moveCard = this.moveCard;
return (
<Card key={card.id} id={card.id} text={card.text} moveCard={moveCard} />
);
},
render: function () {
return (
<div>{this.cardList()}</div>
);
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment