Coherent Coherent - 5 months ago 78
Javascript Question

Issue with setState in React and React-Draggable

I am having difficulties with the setState function in react. I am using the react-draggable package and I can drag my div around but it doesn't appear to be setting the x y coordinates when I release the mouse button, so the div just snaps back to where it was. Can someone tell me what I am doing wrong here with the onControlledDrag? Thanks!

export class DraggableAnswer extends React.Component {
constructor(props, context) {
super(props, context);

this.controlledPosition ={ x: -25, y: 10};
}
onControlledDrag(e, position) {
console.log(position);
const {x, y} = position;
this.setState({
controlledPosition: {x: x, y: y}
});
}


render() {
const dragHandlers = {onStart: this.onStart, onStop: this.onStop};

return (
<div className="draggableAnswerBlock">
<Draggable
zIndex={100}
position={this.controlledPosition}
{...dragHandlers}
onDrag={this.onControlledDrag.bind(this)}>
<div className="box">
Change my position
</div>
</Draggable>
</div>
)
}
}

Answer

in the constructor it should be:

constructor(props, context) {
  super(props, context);

  this.state = { controlledPosition: { x: -25, y: 10} };
}

and then in the return you should pass this.state.controlledPosition into Draggable. Right now this.controlledPosition never updates so it will reset when the drag is done.