Event parameters
- React Native course
- Beginner
- Lesson 79/116
- 5 min
Learn event handler parameters.
The event object
Event handlers take an event parameter. This object carries information about the event: the touch position, the target element, a timestamp and more.
For example onPress={'{(event) => console.log(event)}'}. Here event is the object React Native sends. It has a field called nativeEvent; the real platform data lives there.
Common usage: event.nativeEvent.locationX gives the horizontal touch position. pageY is the vertical position on the page. These are useful for drawing apps or custom gestures.
Using the event parameter
When writing a handler, the parameter name is free; common choices are event or e. The key is writing the prop so the function takes the parameter.
Wrong: onPress={'{handlePress}'} — here handlePress may take a parameter, but a direct reference is used instead of an arrow. This works but the parameter is not visible.
Explicit form: onPress={'{(event) => handlePress(event)}'}. This shows that handlePress takes event. In complex cases, explicit writing makes the code more readable.
Practice Log the touch position
Write an App component. Show <Text>Tap</Text> inside a <TouchableOpacity>. The onPress handler should take event and call console.log(event.nativeEvent.locationX). Export the App function.
Starter code
import { TouchableOpacity, Text } from 'react-native';
// write the touch position log hereSample solution
function App() {
return (
<TouchableOpacity onPress={(event) => console.log(event.nativeEvent.locationX)}>
<Text>Tap</Text>
</TouchableOpacity>
);
}
export default App;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the event parts
| Term | Meaning |
|---|---|
event |
Event object |
nativeEvent |
Native platform data |
locationX |
Horizontal touch position |
pageY |
Vertical page position |
2 How to pass the event to onPress?
- onPress={(event) => ...}
- onPress={event} Correct answer
- onPress={event()}
- onPress=event
Explanation: an arrow function takes the event parameter.
3 Add the event parameter
import { TouchableOpacity, Text } from 'react-native';
function App() {
return (
<TouchableOpacity onPress={(____) => console.log(event.nativeEvent.locationX)}>
<Text>Coord</Text>
</TouchableOpacity>
);
}
import { TouchableOpacity, Text } from 'react-native';
function App() {
return (
<TouchableOpacity onPress={(event) => console.log(event.nativeEvent.locationX)}>
<Text>Coord</Text>
</TouchableOpacity>
);
}
Explanation: the event parameter carries nativeEvent.