React Native
onLongPress
Learn long press with onLongPress.
The onLongPress event
onLongPress fires when the user presses and holds an element. A quick tap triggers onPress, while a long hold triggers onLongPress.
Example: <TouchableOpacity onPress={'{short}'} onLongPress={'{long}'}>. A quick press calls short, a longer hold calls long. This is ideal for context menus or delete confirmations.
The wait time is set with delayLongPress. The default is 500 milliseconds. For example delayLongPress={'{800}'} waits for a longer hold. This avoids accidental triggers.
Tuning delayLongPress
You control how long a long press takes with delayLongPress. The default is 500 milliseconds; sometimes that is too short.
For example, if a long press in a gallery opens a delete menu, delayLongPress={'{700}'} feels safer. A swipe will not accidentally trigger the delete.
The value is in milliseconds. Too low (e.g. 100) causes accidental triggers; too high (e.g. 2000) tries the user's patience. 500-800 is usually a good range.
Exercise Short and long press
Write an App component. Define a count state. Give the <TouchableOpacity> tag both onPress and onLongPress. onPress should call setCount(count + 1), onLongPress should call setCount(count + 5). Export the App function.
Show example solution
function App() {
const [count, setCount] = useState(0);
return (
<TouchableOpacity
onPress={() => setCount(count + 1)}
onLongPress={() => setCount(count + 5)}>
<Text>{count}</Text>
</TouchableOpacity>
);
}
export default App;
Test yourself
-
Add onLongPress
import { TouchableOpacity, Text } from 'react-native';
function App() {
return (
<TouchableOpacity
onPress={() => console.log('Short')}
____={() => console.log('Long')}>
<Text>Press</Text>
</TouchableOpacity>
);
}
Show answer
import { TouchableOpacity, Text } from 'react-native';
function App() {
return (
<TouchableOpacity
onPress={() => console.log('Short')}
onLongPress={() => console.log('Long')}>
<Text>Press</Text>
</TouchableOpacity>
);
}
-
What unit does delayLongPress use?
- Pixels
- Seconds
- Milliseconds
- Percent
Show answer
Pixels — the value is in milliseconds.
-
Match the onLongPress parts
- onLongPress
- Long hold event
- delayLongPress
- Wait time
- 500
- Default value
- onPress
- Quick tap event
Next lesson: Event parameters