Last active
July 23, 2019 22:21
-
-
Save theKashey/9938b2deb486c6550b3575653d589915 to your computer and use it in GitHub Desktop.
Slide "scrollable containers" with you mouse like a... touch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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