Skip to content

Instantly share code, notes, and snippets.

@kitze
Last active January 8, 2019 07:40
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kitze/f4f761436a905c0d3f84e886c090d579 to your computer and use it in GitHub Desktop.
Save kitze/f4f761436a905c0d3f84e886c090d579 to your computer and use it in GitHub Desktop.
A LongPress component for React
import {React, Component} from 'react';
class LongPress extends Component {
shouldShortPress = true;
componentDidMount() {
this.listenForTouch();
}
componentWillUnmount() {
this.stopListening();
}
startInterval = () => {
this.timeout = setTimeout(this.longPressed, this.props.time);
};
longPressed = () => {
this.shouldShortPress = false;
if (this.props.onLongPress) {
this.props.onLongPress();
this.cancelInterval();
}
};
cancelInterval = () => {
clearTimeout(this.timeout);
if (this.props.onPress && this.shouldShortPress) {
this.props.onPress();
}
};
setRef = ref => (this.ref = ref);
listenForTouch = () => {
if (this.ref) {
this.listenerStart = this.ref.addEventListener('touchstart', e => {
e.preventDefault();
this.shouldShortPress = true;
this.startInterval();
});
this.listenerEnd = this.ref.addEventListener('touchend', e => {
e.preventDefault();
this.cancelInterval();
});
}
};
stopListening = () => {
this.ref.removeEventListener('touchstart', this.listenerStart);
this.ref.removeEventListener('touchend', this.listenerEnd);
};
render() {
return this.props.render(this.setRef);
}
}
export default LongPress;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment