Skip to content

Instantly share code, notes, and snippets.

@jimjam88
Created August 9, 2022 14:55
Show Gist options
  • Save jimjam88/f9400de4615a2223f5d4c6d4a6141639 to your computer and use it in GitHub Desktop.
Save jimjam88/f9400de4615a2223f5d4c6d4a6141639 to your computer and use it in GitHub Desktop.
Hook to handle single/double taps in react native
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;
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