Skip to content

Instantly share code, notes, and snippets.

@eugenserbanescu
Last active February 8, 2018 10:11
Show Gist options
  • Save eugenserbanescu/a7d4fe25454a9e6d6e58b9a6180c716b to your computer and use it in GitHub Desktop.
Save eugenserbanescu/a7d4fe25454a9e6d6e58b9a6180c716b to your computer and use it in GitHub Desktop.
Draggable panel in react (initial take)
import React, { Component } from "react";
class Panel extends Component {
state = {
width: 200,
dragging: false,
offset: 0
};
dragStart = e => {
this.setState({ dragging: true });
document.addEventListener("mousemove", this.drag);
document.addEventListener("mouseup", this.dragStop);
};
drag = e => {
if (this.state.dragging) {
this.setState({
width: e.clientX - this.state.offset
});
}
};
dragStop = e => {
this.setState({ dragging: false });
document.removeEventListener("mouseup", this.dragStop);
document.removeEventListener("mousemove", this.drag);
};
setWrapperRef = ref => {
this.wrapper = ref;
};
componentDidMount() {
this.setState({
offset: this.wrapper.offsetLeft
});
}
render() {
return (
<div
ref={this.setWrapperRef}
style={{
flexDirection: "row",
width: this.state.width
}}
>
<div>{this.props.children}</div>
<div
style={{
width: "0",
border: "1px solid red",
height: "100vh",
marginLeft: "auto"
}}
onMouseDown={this.dragStart}
/>
</div>
);
}
}
export default Panel;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment