I created a component which allows for a drag and scroll functionality. The problem I have now is that I don't know how to add momentum to the scroll on mouse up (and also but that's not that important a bounce effect). The important part is: How do I update a component over some period of time (depending how strong was the drag)?
Below my scroll component code:
class DraggingScrollView extends React.Component {
constructor(props) {
super(props);
this.state = {
isScrolling: false,
scrollLeft: 0,
clientX: 0,
};
this.scrollContainer = React.createRef();
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.handleScroll = this.handleScroll.bind(this);
}
componentWillUpdate(nextProps, nextState) {
const { isScrolling } = this.state;
if (isScrolling !== nextState.isScrolling) {
this.setScrollingEnabled(nextState.isScrolling);
}
}
setScrollingEnabled(isEnabled) {
if (isEnabled) {
window.addEventListener('mousemove', this.handleScroll);
} else {
window.removeEventListener('mousemove', this.handleScroll);
}
}
handleMouseDown(event) {
const { clientX } = event;
const { scrollLeft } = this.scrollContainer.current;
this.setState({
isScrolling: true,
scrollLeft,
clientX,
});
}
handleMouseUp() {
this.setState({
isScrolling: false,
scrollLeft: 0,
clientX: 0,
});
}
handleScroll(event) {
const { scrollLeft, clientX } = this.state;
const scrollContainer = this.scrollContainer.current;
const scrollDestination = scrollLeft + clientX - event.clientX;
scrollContainer.scrollLeft = scrollDestination;
}
render() {
const { children, scrollContainerHeight } = this.props;
return (
<div
id="scrollContainer"
ref={this.scrollContainer}
role="presentation"
style={{ paddingTop: scrollContainerHeight }}
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}
>
<div id="scrollContentContainer">{children}</div>
</div>
);
}
}