Skip to content

Instantly share code, notes, and snippets.

@amerllica
Last active June 28, 2021 12:01
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 amerllica/3488cd5711660e9fd95efe362fccffd6 to your computer and use it in GitHub Desktop.
Save amerllica/3488cd5711660e9fd95efe362fccffd6 to your computer and use it in GitHub Desktop.
Google horizontal scroll for desktop (ReactJS)
import { useEffect } from 'react';
import type { MutableRefObject } from 'react';
const useHorizontalScroll = (
scrollWrapperRef?: MutableRefObject<HTMLElement | undefined>,
scrollSpeed = 1
): void => {
useEffect(() => {
const horizWrapper = scrollWrapperRef?.current;
if (horizWrapper?.style) {
horizWrapper.style.overflow = 'auto';
horizWrapper.style.flexShrink = '0';
}
let isDown = false;
let startX: number;
let scrollLeft: number;
horizWrapper?.addEventListener('mousedown', (e: any) => {
isDown = true;
startX = e.pageX - horizWrapper?.offsetLeft;
scrollLeft = horizWrapper?.scrollLeft;
});
horizWrapper?.addEventListener('mouseleave', () => {
isDown = false;
});
horizWrapper?.addEventListener('mouseup', () => {
isDown = false;
});
horizWrapper?.addEventListener('mousemove', (e: any) => {
if (!isDown) return;
e.preventDefault();
const x = e.pageX - horizWrapper?.offsetLeft;
const walk = (x - startX) * scrollSpeed;
horizWrapper.scrollLeft = scrollLeft - walk;
});
}, [scrollSpeed, scrollWrapperRef]);
};
export default useHorizontalScroll;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment