CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

App.js
import { useState } from 'react';
import { TouchableOpacity, Text } from 'react-native';

// write the short and long press here

Sample solution

App.js
function App() {
  const [count, setCount] = useState(0);
  return (
    <TouchableOpacity
      onPress={() => setCount(count + 1)}
      onLongPress={() => setCount(count + 5)}>
      <Text>{count}</Text>
    </TouchableOpacity>
  );
}
export default App;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Add onLongPress

Question
import { TouchableOpacity, Text } from 'react-native';

function App() {
  return (
    <TouchableOpacity
      onPress={() => console.log('Short')}
      ____={() => console.log('Long')}>
      <Text>Press</Text>
    </TouchableOpacity>
  );
}
Answer
import { TouchableOpacity, Text } from 'react-native';

function App() {
  return (
    <TouchableOpacity
      onPress={() => console.log('Short')}
      onLongPress={() => console.log('Long')}>
      <Text>Press</Text>
    </TouchableOpacity>
  );
}

Explanation: onLongPress listens for a long hold.

2 What unit does delayLongPress use?

  • Pixels Correct answer
  • Seconds
  • Milliseconds
  • Percent

Explanation: the value is in milliseconds.

3 Match the onLongPress parts

Term Meaning
onLongPress Long hold event
delayLongPress Wait time
500 Default value
onPress Quick tap event

All lessons in Beginner