Handling Double and Single tap on React Native
1 min readNov 12, 2023
To handle both single and double taps on a video component in React Native, and perform different actions for each, you can use a combination of state management and the TouchableOpacity
component. Below is an example:
import React, { useState, useRef } from 'react';
import { TouchableOpacity, View, Text, Video } from 'react-native';
const VideoPlayer = () => {
const [isPlaying, setPlaying] = useState(false);
const lastTapTimeRef = useRef(null);
const handleTap = () => {
const now = new Date().getTime();
const DOUBLE_TAP_DELAY = 300; // Adjust as needed for your use case (in milliseconds)
if (now - lastTapTimeRef.current < DOUBLE_TAP_DELAY) {
// Double tap detected
console.log('Double tap!');
// Perform 'like' action here
} else {
// Single tap detected
console.log('Single tap!');
// Toggle play/pause video
setPlaying(!isPlaying);
}
lastTapTimeRef.current = now;
};
return (
<View>
<TouchableOpacity onPress={handleTap}>
<Video
source={{ uri: 'your_video_url_here' }}
style={{ width: 300, height: 200 }}
paused={!isPlaying}
/>
</TouchableOpacity>
</View>
);
};
export default VideoPlayer;