Skip to content

Instantly share code, notes, and snippets.

@daino3
Created July 8, 2020 21:19
Show Gist options
  • Save daino3/c54d23b5b79d78e1e42baec40c6ba3e8 to your computer and use it in GitHub Desktop.
Save daino3/c54d23b5b79d78e1e42baec40c6ba3e8 to your computer and use it in GitHub Desktop.
import React from 'react';
import { useSpring, animated } from 'react-spring';
import { useDrag } from 'react-use-gesture';
import PropTypes from 'prop-types';
const THRESHOLD_PX = 100;
function AnimatedSwipeNavigation({ onSwipeLeft, onSwipeRight, vertical = false, horizontal = true, children }) {
const [{ x, y }, set] = useSpring(() => ({ x: 0, y: 0 }));
// Set the drag hook and define component movement based on gesture data
const bind = useDrag(({ down, movement: [x, y], cancel }) => {
// we don't want both horizontal & vertical gestures
y = vertical ? y : 0;
x = horizontal ? x : 0;
// Did you move far enough to trigger a swipe gesture?
const didMoveFarEnough = Math.abs(x) > THRESHOLD_PX || Math.abs(y) > THRESHOLD_PX;
// pair with 'down' otherwise, you'll fire 2 requests
if (didMoveFarEnough && down) {
cancel();
if (x < 0) {
onSwipeLeft();
} else {
onSwipeRight();
}
}
set({
x: down ? x : 0,
y: down ? y : 0,
scale: down ? 1.2 : 1,
immediate: down,
});
});
// Bind it to a component
return (
<animated.div {...bind()} style={{ x, y }} >
{children}
</animated.div>
);
}
AnimatedSwipeNavigation.propTypes = {
children: PropTypes.object.isRequired,
horizontal: PropTypes.bool,
vertical: PropTypes.bool,
// funcs
onSwipeLeft: PropTypes.func.isRequired,
onSwipeRight: PropTypes.func.isRequired,
};
AnimatedSwipeNavigation.defaultProps = {
horizontal: true,
vertical: false,
};
export default AnimatedSwipeNavigation;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment