Skip to content

Instantly share code, notes, and snippets.

@AnishLushte07
Created October 9, 2020 17:04
Show Gist options
  • Save AnishLushte07/055144cb50130f11743cf2c2920d10e0 to your computer and use it in GitHub Desktop.
Save AnishLushte07/055144cb50130f11743cf2c2920d10e0 to your computer and use it in GitHub Desktop.
ReactJS Custom hook for swipe gesture on mobile browser using Hammer.js
/*
* Swipe hook gives functionality to detect user swipe event on give container.
* Dependency: hammerjs (npm install hammerjs --save)
*
* e.g
* Component.js
* const swipeContainerRef = useRef();
* useSwipeHook(swipeContainerRef, leftSwipeCallback, rightSwipeCallback)
* <div ref={swipeContainerRef}>Swipe hook will catch events for this container</div>
*
* Functionality of hook can be extended by passing single callback for all events
* and pass type of hook to callback.
*
* Callback functions are stored using ref to avoid rerunning of useEffect.
* This avoid extra work of consumer component
*/
import { useRef, useEffect } from 'react';
import Hammer from 'hammerjs';
export default function useSwipe(elRef, leftSwipe, rightSwipe) {
const leftSwipeRef = useRef();
leftSwipeRef.current = leftSwipe;
const rightSwipeRef = useRef();
rightSwipeRef.current = rightSwipe;
useEffect(() => {
if (!elRef || !elRef.current) {
console.error('UseSwipe hook need reference of swipe container');
return;
}
const container = elRef.current;
const HammerScroll = new Hammer.Manager(container);
const Swipe = new Hammer.Swipe();
HammerScroll.add(Swipe);
HammerScroll.on('swipeleft', () => leftSwipeRef.current());
HammerScroll.on('swiperight', () => rightSwipeRef.current());
return () => {
HammerScroll.off('swipeleft');
HammerScroll.off('swiperight');
};
}, [leftSwipeRef, rightSwipeRef]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment