Skip to content

Instantly share code, notes, and snippets.

@igolopolosov
Last active August 31, 2017 12:45
Show Gist options
  • Select an option

  • Save igolopolosov/55a56b2e8cd135d902c197153bbf110c to your computer and use it in GitHub Desktop.

Select an option

Save igolopolosov/55a56b2e8cd135d902c197153bbf110c to your computer and use it in GitHub Desktop.
Simple way to create component with scrolling by drag.
import React from 'react';
import ReactDOM from 'react-dom';
/**
* Div with scroll by drag.
*/
export class Scrollable extends React.Component<any, any> {
SPEED = 2.5;
constructor(props: any, state: any) {
super(props, state);
this.state = {
scrollable: null
};
this.onStart = this.onStart.bind(this);
this.onStop = this.onStop.bind(this);
this.onMove = this.onMove.bind(this);
}
componentDidMount() {
const scrollable = ReactDOM.findDOMNode(this.refs['scrollable']);
this.setState({
scrollable
});
scrollable.addEventListener('mousedown', this.onStart);
scrollable.addEventListener('mouseup', this.onStop);
scrollable.addEventListener('mouseleave', this.onStop);
}
componentWillUnmount() {
const { scrollable } = this.state;
scrollable.removeEventListener('mousedown', this.onStart);
scrollable.removeEventListener('mouseup', this.onStop);
scrollable.removeEventListener('mouseleave', this.onStop);
scrollable.removeEventListener('mousemove', this.onMove);
}
onStart(e: MouseEvent) {
const hasScroll = this.state.scrollable.clientHeight !== this.state.scrollable.scrollHeight;
if (hasScroll) {
scrollable.addEventListener('mousemove', this.onMove);
}
}
onStop(e: MouseEvent) {
this.state.scrollable.removeEventListener('mousemove', this.onMove);
}
onMove(e: MouseEvent) {
this.state.scrollable.scrollTop += e.movementY * this.SPEED;
}
render() {
let { children, ...other } = this.props;
return <div ref='scrollable' {...other}>{children}</div>;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment