Created
August 9, 2022 14:55
-
-
Save jimjam88/f9400de4615a2223f5d4c6d4a6141639 to your computer and use it in GitHub Desktop.
Hook to handle single/double taps in 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 { Pressable, Text } from 'react-native'; | |
import { useDoubleTapHandler } from './useDoubleTapHandler'; | |
const UsageExample = () => { | |
const onPressHandler = useDoubleTapHandler(); | |
const onPress = () => { | |
onPressHandler({ | |
onSinglePress: () => console.log('Single Tap'), | |
onDoublePress: () => console.log('Double Tap'), | |
}); | |
}; | |
return ( | |
<Pressable onPress={onPress}> | |
<Text>Tap me</Text> | |
</Pressable> | |
); | |
}; | |
export default UsageExample; |
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 { useState } from 'react'; | |
const DOUBLE_TAP_DELAY_MS = 300; | |
let timerId; | |
export const useDoubleTapHandler = () => { | |
const [lastTapTime, setLastTapTime] = useState(0); | |
return ({ onSingleTap, onDoubleTap }) => { | |
clearTimeout(timerId); | |
const now = Date.now(); | |
const delta = now - lastTapTime; | |
if (delta <= DOUBLE_TAP_DELAY_MS) { | |
onDoubleTap(); | |
} else { | |
timerId = setTimeout(onSingleTap, DOUBLE_TAP_DELAY_MS + 1); | |
} | |
setLastTapTime(now); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment