Last active
January 8, 2019 07:40
-
-
Save kitze/f4f761436a905c0d3f84e886c090d579 to your computer and use it in GitHub Desktop.
A LongPress component for React
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 {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