Skip to content

Instantly share code, notes, and snippets.

@gabsprates
Created June 1, 2019 14:39
Show Gist options
  • Save gabsprates/a6302cddb86b7b9afb60d8af0292e13a to your computer and use it in GitHub Desktop.
Save gabsprates/a6302cddb86b7b9afb60d8af0292e13a to your computer and use it in GitHub Desktop.
import React from "react";
type Props = {
onDrop: (x: number) => void;
};
type State = {
left: number;
moving: boolean;
};
enum MouseEvents {
UP = "mouseup",
OUT = "mouseout",
DOWN = "mousedown",
MOVE = "mousemove"
}
export class DragImage extends React.Component<Props, State> {
startAt: number | null = null;
constructor(props: Props) {
super(props);
this.state = { left: 0, moving: false };
this.handleMove = this.handleMove.bind(this);
}
handleMove(e: React.MouseEvent<HTMLDivElement>) {
e.preventDefault();
const target = e.nativeEvent.target as HTMLElement;
const parent = target.parentElement as HTMLElement;
let movedPixels = this.startAt
? this.startAt - e.nativeEvent.offsetX
: e.nativeEvent.offsetX;
movedPixels = this.state.left + movedPixels;
if (movedPixels < 0) {
movedPixels = 0;
} else if (movedPixels > target.offsetWidth - parent.offsetWidth) {
movedPixels = target.offsetWidth - parent.offsetWidth;
}
if (e.type === MouseEvents.OUT || e.type === MouseEvents.UP) {
this.setState({ moving: false });
this.startAt = null;
} else if (e.type === MouseEvents.DOWN) {
this.setState({ moving: true });
this.startAt = e.nativeEvent.offsetX;
} else if (this.state.moving) {
this.setState({ left: movedPixels }, () => {
this.props.onDrop(movedPixels);
});
}
}
render() {
return (
<div
style={{
width: "975px",
height: "250px",
margin: "0 auto",
overflow: "hidden",
position: "relative"
}}
>
<img
style={{
top: "0",
height: "auto",
maxWidth: "1182px",
marginLeft: -1 * this.state.left
}}
src="http://placehold.it/2364x500"
/>
<div
style={{
top: "0",
width: "1182px",
height: "250px",
position: "absolute",
left: -1 * this.state.left
}}
className="featured-drag"
onMouseMove={this.handleMove}
onMouseDown={this.handleMove}
onMouseUp={this.handleMove}
onMouseOut={this.handleMove}
/>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment