React Native
Event parameters
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.
Exercise 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.
Show example solution
function App() {
return (
<TouchableOpacity onPress={(event) => console.log(event.nativeEvent.locationX)}>
<Text>Tap</Text>
</TouchableOpacity>
);
}
export default App;
Test yourself
-
Match the event parts
- event
- Event object
- nativeEvent
- Native platform data
- locationX
- Horizontal touch position
- pageY
- Vertical page position
-
How to pass the event to onPress?
- onPress={(event) => ...}
- onPress={event}
- onPress={event()}
- onPress=event
Show answer
onPress={event} — an arrow function takes the event parameter.
-
Add the event parameter
import { TouchableOpacity, Text } from 'react-native';
function App() {
return (
<TouchableOpacity onPress={(____) => console.log(event.nativeEvent.locationX)}>
<Text>Coord</Text>
</TouchableOpacity>
);
}
Show answer
import { TouchableOpacity, Text } from 'react-native';
function App() {
return (
<TouchableOpacity onPress={(event) => console.log(event.nativeEvent.locationX)}>
<Text>Coord</Text>
</TouchableOpacity>
);
}
Next lesson: onLayout