Created
March 9, 2020 21:27
-
-
Save casprine/f8539859f8492f0ae5f097b93ceb9a05 to your computer and use it in GitHub Desktop.
DoubleTap component for React Native
This file contains 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 from "react"; | |
import { TouchableOpacity } from "react-native" | |
const DoubleTap = ({ children, delay, doubleTap, singleTap, ...rest }) => { | |
let timer = false; | |
let firstPress = true; | |
let delayTime = delay; | |
let lastTime = new Date(); | |
return ( | |
<TouchableOpacity onPress={() => onTap()} {...rest}> | |
{children} | |
</TouchableOpacity> | |
); | |
function onTap() { | |
let now = new Date().getTime(); | |
if (firstPress) { | |
firstPress = false; | |
timer = setTimeout(() => { | |
singleTap && singleTap(); | |
firstPress = true; | |
timer = false; | |
}, delayTime); | |
lastTime = now; | |
} else { | |
if (now - lastTime < delayTime) { | |
timer && clearTimeout(timer); | |
doubleTap && doubleTap(); | |
firstPress = true; | |
} | |
} | |
} | |
}; | |
DoubleTap.defaultProps = { | |
delay: 150, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment