I'm getting back into React and am wanting to have some components which can be dragged around by the user on the website I'm making. Note, by draggable I mean 'moved around the page by mouse', not the 'drag and drop' kind of draggable.
My code so far kind of works but is a bit jerky and does not always register when the mouse is up/released.
This is the component I'm trying to make draggable.
import React from 'react';
export default class Folder extends React.Component {
constructor(props) {
super(props);
this.state = {mouseDown: false,
name: props.name,
left: props.left,
top:props.top
};
}
// mouse down -> grab coords and offset
// mouse move, if mouse down true, make mouse coords
// folder coords
// on mouse up change mouse down to false.(can't move)
mouseHandler(e){
this.setState({mouseDown: true})
}
mouseMove(e){
if(!this.state.mouseDown){
return
}else{
console.log('mouse held and moving')
let newLeft = e.clientX - e.nativeEvent.offsetX
let newTop = e.clientY - e.nativeEvent.offsetY
this.setState({left: newLeft, top:newTop})
}
}
mouseUp(e){
this.setState({mouseDown: false})
console.log('mouse up')
}
render() {
return (<div className="icon"
onMouseDown={(e) => this.mouseHandler(e)}
onMouseMove={(e) => this.mouseMove(e)}
onMouseUp={(e) => this.mouseUp(e)}
style={{top: this.state.top, left: this.state.left}} >
<div className="tab"></div>
<div className="foldergap"></div>
<div className="foldertitle"><p>{this.state.name}</p>/div>
</div>)
}
};
I know there are libraries I could use but I would like to use my own work where I can. I have also seen this similar question but the answers either seemed to use outdated techniques, DOM manipulation (which doesn't seem like the 'React way') or libraries.
My question is what am I doing wrong and what is the recommended way of achieving this functionality?
Thank you.