onPress
- React Native course
- Beginner
- Lesson 77/116
- 4 min
Learn the press event with onPress.
The onPress event
onPress fires when the user taps an element. If you want something to happen on a button press, you pass a function to the onPress prop.
You saw onPress with TouchableOpacity in the Counter project. Now we go deeper on the event side. Example: <TouchableOpacity onPress={'{() => console.log('Tapped')}'}}>. Each press logs to the console.
The function can be passed directly as {`{handlePress}`} or as an arrow function {`{() => handlePress()}`}. Use the arrow form when you need to pass parameters; otherwise the direct reference is cleaner.
Passing a function to onPress
You can pass a function to onPress in two ways. Direct reference: onPress={'{handlePress}'}. This hands the function as is.
Or inside an arrow function: onPress={'{() => handlePress()}'}. Use this when you need to pass parameters or call several things. For example {`{() => { setCount(count + 1); log(); }}`}.
Important pitfall: do not write onPress={'{handlePress()}'}. That calls the function immediately during render; it does not wait for the tap. Always pass the function itself.
Practice A button that increments a number
Write an App component. Define count with useState(0). Put <Text>{`{count}`}</Text> inside a <TouchableOpacity>. Call setCount(count + 1) on onPress. Export the App function.
Starter code
import { useState } from 'react';
import { TouchableOpacity, Text } from 'react-native';
// write the button hereSample solution
function App() {
const [count, setCount] = useState(0);
return (
<TouchableOpacity onPress={() => setCount(count + 1)}>
<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 When does onPress fire?
- Every second
- When the component mounts
- Only on launch
- When the user taps Correct answer
Explanation: Answer: when the user taps. onPress listens for the tap gesture.
2 Add onPress
import { TouchableOpacity, Text } from 'react-native';
function App() {
return (
<TouchableOpacity ____={() => console.log('Tapped')}>
<Text>Press</Text>
</TouchableOpacity>
);
}
import { TouchableOpacity, Text } from 'react-native';
function App() {
return (
<TouchableOpacity onPress={() => console.log('Tapped')}>
<Text>Press</Text>
</TouchableOpacity>
);
}
Explanation: onPress listens for the tap event.
3 Match the onPress parts
| Term | Meaning |
|---|---|
onPress |
Tap event |
handlePress |
Handler function |
() => ... |
Arrow function |
TouchableOpacity |
Tappable component |