Skip to content

Instantly share code, notes, and snippets.

@theKashey
Last active July 23, 2019 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theKashey/9938b2deb486c6550b3575653d589915 to your computer and use it in GitHub Desktop.
Save theKashey/9938b2deb486c6550b3575653d589915 to your computer and use it in GitHub Desktop.
Slide "scrollable containers" with you mouse like a... touch
import {useState, useEffect, useLayoutEffect, useRef} from "react";
const getMouseCoords = (e) => [e.clientX, e.clientY];
const useDragHandle = (ref) => {
const [mouseDown, setMouseDown] = useState(null);
const [initialScroll, setInitialScroll] = useState(null);
useEffect(() => {
const {current: container} = ref;
const onMouseDown = (e) => {
setMouseDown(getMouseCoords(e));
setInitialScroll([container.scrollLeft, container.scrollTop]);
e.preventDefault();
};
container.addEventListener('mousedown', onMouseDown);
return () => container.removeEventListener('mousedown', onMouseDown);
}, []);
useLayoutEffect(() => {
if (mouseDown) {
const {current: container} = ref;
const onMouseUp = () => setMouseDown(null);
const onMouseMove = (e) => {
const coords = getMouseCoords(e);
container.scrollLeft = initialScroll[0] + (mouseDown[0] - coords[0]);
container.scrollTop = initialScroll[1] + (mouseDown[1] - coords[1]);
e.preventDefault();
};
window.addEventListener('mouseup', onMouseUp);
window.addEventListener('mousemove', onMouseMove);
return () => {
window.removeEventListener('mouseup', onMouseUp);
window.removeEventListener('mousemove', onMouseMove);
}
}
return () => null;
}, [mouseDown, initialScroll]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment