Skip to content

Instantly share code, notes, and snippets.

@eudoxia0
Last active July 29, 2016 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eudoxia0/71bfac03038db4717386173bb3cc2f3b to your computer and use it in GitHub Desktop.
Save eudoxia0/71bfac03038db4717386173bb3cc2f3b to your computer and use it in GitHub Desktop.
React drag and drop
.bin {
width: 300px;
margin: 35px auto;
padding: 45px;
color: white;
font-size: 2em;
text-align: center;
border-radius: 5px;
}
var Bin = React.createClass({
mixins: [DragDropMixin],
getInitialState: function() {
return { items: [] };
},
addItem: function(name) {
clone = this.state.items.slice(0);
clone.push(name);
this.setState({ items: clone });
},
render: function() {
const dropState = this.getDropState(ItemTypes.ITEM);
var stateClass = 'none';
if (dropState.isHovering) {
stateClass = 'hovering';
} else if (dropState.isDragging) {
stateClass = 'dragging';
}
const dropped = this.state.items.map(function(name) {
return <li>{name}</li>;
});
return (
<div className={'bin bin-state-' + stateClass}
{...this.dropTargetFor(ItemTypes.ITEM)}>
{dropState.isHovering ?
'Release to drop' :
'Drag item here'}
<ul className="dropped">
{dropped}
</ul>
</div>
);
}
});
.bin-state-none {
background-color: #34495E;
}
.bin-state-dragging {
background-color: #E98B39;
}
.bin-state-hovering {
background-color: #2ECC71;
}
statics: {
configureDragDrop: function(register) {
register(ItemTypes.ITEM, {
dropTarget: {
acceptDrop: function(component, item) {
component.addItem(item.name);
}
}
});
}
},
body {
margin: 0;
padding: 0;
min-height: 100vh;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
var Container = React.createClass({
render: function() {
return (
<div>
<Bin />
<ul className='items'>
<Item name='Glass' />
<Item name='Metal' />
<Item name='Paper' />
</ul>
</div>
);
}
});
React.render(
<Container />,
document.body
);
.dropped {
margin: 20px 0;
padding: 0;
}
.dropped li {
list-style-type: none;
font-size: 0.6em;
}
var Item = React.createClass({
mixins: [DragDropMixin],
statics: {
configureDragDrop: function(register) {
register(ItemTypes.ITEM, {
dragSource: {
beginDrag: function(component) {
return {
item: {
name: component.props.name
}
};
}
}
});
}
},
render: function () {
return (
<li className='item'
{...this.dragSourceFor(ItemTypes.ITEM)}>
{this.props.name}
</li>
);
}
});
const ItemTypes = {
ITEM: 'item'
};
.items {
padding: 0;
text-align: center;
}
.item {
display: inline-block;
padding: 20px;
margin: 25px 10px;
border: 2px solid #E74C3C;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment