Last active
March 1, 2016 21:15
-
-
Save JavascriptMick/24a9328aea20b2e22d4c to your computer and use it in GitHub Desktop.
Adding Draggable behaviour to a React component
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 React from "react"; | |
export default class DraggableComponent extends React.Component{ | |
constructor(props){ | |
super(props); | |
this.isDragging = false; | |
this.originalClientX = 0; | |
this.originalClientY = 0; | |
this.originalTop = 0; | |
this.originalLeft = 0; | |
this.state = { | |
top: '0px', | |
left: '0px' | |
} | |
} | |
render(){ | |
let dragStyle = {position: 'absolute', top: this.state.top ,left: this.state.left}; | |
console.log('dragStyle:' + dragStyle); | |
return( | |
<textarea | |
defaultValue={"I am draggable"} | |
class={"red-note"} | |
style={dragStyle} | |
onMouseDown={this.onMouseDown.bind(this)} | |
onMouseMove={this.onMouseMove.bind(this)} | |
onMouseUp={this.onMouseUp.bind(this)} | |
/> | |
); | |
} | |
onMouseDown($event){ | |
if($event.target.style.position=='absolute' && $event.target.style.left && $event.target.style.top){ | |
this.isDragging = true; | |
this.originalLeft = parseInt($event.target.style.left, 10); | |
this.originalTop = parseInt($event.target.style.top, 10); | |
this.originalClientX = $event.clientX; | |
this.originalClientY = $event.clientY; | |
}else{ | |
console.log('draggable: Error! the annotated ' + $event.target.nodeName + ' element needs to be inline styled with position, top and left'); | |
} | |
} | |
onMouseMove($event){ | |
if(this.isDragging){ | |
this.setState({ | |
top: this.originalTop + ($event.clientY - this.originalClientY), | |
left: this.originalLeft + ($event.clientX - this.originalClientX) | |
}); | |
} | |
} | |
onMouseUp($event){ | |
if(this.isDragging){ | |
this.isDragging = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment